正则表达式匹配括号之间的内容 [英] RegEx to match stuff between parentheses
问题描述
我很难让它发挥作用.我有一个像这样的字符串:
something/([0-9])/([a-z])
而且我需要正则表达式或获取括号之间的每个匹配项并返回匹配数组的方法,例如:
<预><代码>[[0-9],[a-z]]我使用的正则表达式是 /\((.+)\)/
它似乎匹配正确的东西 if 只有 one 一组括号.
如何使用 JavaScript 中的任何 RegExp 方法获取上述数组?我只需要返回该数组,因为数组中返回的 项将被循环以创建 URL 路由方案.
您需要通过添加?"来使您的正则表达式模式非贪婪"在.+"之后
默认情况下,'*' 和 '+' 是贪婪的,因为它们将匹配尽可能长的字符字符串,忽略字符串中可能出现的任何匹配.
非贪婪使模式只匹配最短的匹配项.
请参阅注意贪婪!以获得更好的解释.
或者,将正则表达式更改为
\(([^\)]+)\)
将匹配任何本身不包含括号的括号分组.
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.
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.
You need to make your regex pattern 'non-greedy' by adding a '?' after the '.+'
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
\(([^\)]+)\)
which will match any grouping of parens that do not, themselves, contain parens.
这篇关于正则表达式匹配括号之间的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!