RegEx匹配括号之间的东西 [英] RegEx to match stuff between parentheses

查看:443
本文介绍了RegEx匹配括号之间的东西的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难让这个工作。我有一个字符串:

I'm having a tough time getting this to work. I have a string like:

something/([0-9])/([a-z])

我需要正则表达式或一种方法来获取括号之间的每个匹配并返回一系列匹配项,如:

And I need regex or a method of getting each match between the parentheses and return an array of matches like:

[
  [0-9],
  [a-z]
]

我使用的正则表达式是 / \((。+)\)/ 哪个似乎与正确的东西相匹配如果只有一个一组括号。

The regex I'm using is /\((.+)\)/ which does seem to match the right thing if there is only one set of parenthesis.

如何使用JavaScript中的任何RegExp方法获取上面的数组?我需要返回该数组,因为数组中的返回项将循环通过以创建URL路由方案。

How can I get an array like above using any RegExp method in JavaScript? I need to return just that array because the returned items in the array will be looped through to create a URL routing scheme.

推荐答案

你需要在'。+'

默认情况下,' *'和'+'是贪婪的,因为它们会匹配尽可能长的字符串,忽略字符串中可能出现的任何匹配。

By default, '*' and '+' are greedy in that they will match as long a string of chars as possible, ignoring any matches that might occur within the string.

非贪婪使模式只匹配最短的匹配。

Non-greedy makes the pattern only match the shortest possible match.

参见注意贪婪!以获得更好的解释。

See Watch Out for The Greediness! for a better explanation.

或者,将你的正则表达式更改为

Or alternately, change your regex to

\(([^\)]+)\)

将匹配任何不包含parens的parens组合。

which will match any grouping of parens that do not, themselves, contain parens.

这篇关于RegEx匹配括号之间的东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆