Javascript 正则表达式匹配括号之间的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6208367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:45:44  来源:igfitidea点击:

RegEx to match stuff between parentheses

javascriptregexarraysurlurl-routing

提问by Oscar Godson

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 ifthere is only oneset 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 returneditems in the array will be looped through to create a URL routing scheme.

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

回答by Rob Raisch

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.

这将匹配本身不包含括号的任何括号分组。

回答by Chandu

Use this expression:

使用这个表达式:

/\(([^()]+)\)/g

e.g:

例如:

function()
{
    var mts = "something/([0-9])/([a-z])".match(/\(([^()]+)\)/g );
    alert(mts[0]);
    alert(mts[1]);
}

回答by maerics

var getMatchingGroups = function(s) {
  var r=/\((.*?)\)/g, a=[], m;
  while (m = r.exec(s)) {
    a.push(m[1]);
  }
  return a;
};

getMatchingGroups("something/([0-9])/([a-z])"); // => ["[0-9]", "[a-z]"]

回答by arturh

If s is your string:

如果 s 是您的字符串:

s.replace(/^[^(]*\(/, "") // trim everything before first parenthesis
 .replace(/\)[^(]*$/, "") // trim everything after last parenthesis
 .split(/\)[^(]*\(/);      // split between parenthesis