简体   繁体   English

用于匹配括号中值的正则表达式/ Javascript

[英]Regex/Javascript for Matching Values in Parenthesis

My web application needs to parse numeric ranges in strings that are enclosed by parenthesis. 我的Web应用程序需要解析括号括起来的字符串中的数字范围。 I've never really understood regex properly so I need some assistance. 我从来没有真正理解正则表达式,所以我需要一些帮助。 The code below is kind of what I'm looking to do (I'll then split the string on the hyphen and get the min/max values). 下面的代码是我想要做的事情(然后我会在连字符上分割字符串并获取最小/最大值)。 Obviously the pattern is wrong - the example below alerts "(10-12) foo (5-10) bar" when my desired result is 1 alert saying (10-12) and the next saying (5-10), or better yet those values without the parenthesis if that's possible. 显然这种模式是错误的 - 下面的例子警告“(10-12)foo(5-10)bar”当我想要的结果是1个警告说(10-12)和下一个说法(5-10),或者更好那些没有括号的值,如果可能的话。

Any assistance is appreciated. 任何帮助表示赞赏。

var string = "foo bar (10-12) foo (5-10) bar";
var pattern = /\(.+\)/gi;
matches = string.match(pattern);

for (var i in matches) {
    alert(matches[i]);
}

Make your quantifier lazy by adding a ? 通过添加?使你的量词变得懒惰? after the + . + Otherwise, it will greedily consume as much as possible, from your opening ( to the last ) in the string. 否则,它将从字符串的开头(到最后一个)贪婪地消耗掉。

var string = "foo bar (10-12) foo (5-10) bar",
    pattern = /\(.+?\)/g,
    matches = string.match(pattern);

jsFiddle . jsFiddle

If you don't want to include the parenthesis in your matches, generally you'd use a positive lookahead and lookbehind for parenthesis. 如果您不想在匹配中包括括号,通常您会使用正向前瞻和后视括号。 JavaScript doesn't support lookbehinds (though you can fake them). JavaScript不支持lookbehinds(虽然你可以伪造它们)。 So, use... 所以,用...

var string = "foo bar (10-12) foo (5-10) bar",
    pattern = /\((.+?)\)/g,
    match,
    matches = [];

while (match = pattern.exec(string)) {
    matches.push(match[1]);
}

jsFiddle . jsFiddle

Also... 也...

  • You don't need the i flag in your regex; 你的正则表达式中不需要i标志; you don't match any letters. 你不匹配任何字母。
  • You should always scope your variables with var . 您应该始终使用var变量的范围。 In your example, matches will be global. 在您的示例中, matches将是全局的。
  • You shouldn't use a for (in) to iterate over an array. 您不应该使用for (in)来迭代数组。 You should also check that match() doesn't return null (if no results were found). 您还应检查match()是否返回null (如果未找到结果)。

The problem is that your regular expression is Greedy , meaning that it will match the first bracket and keep on going till it finds the last bracket. 问题是你的正则表达式是贪婪的 ,这意味着它将匹配第一个括号并继续前进,直到它找到最后一个括号。 To fix this you have two options, you either add the ? 要解决此问题,您有两个选择,您要么添加? symbol after the + to make it non greedy: \\(.+?\\) or else, match any character except a closing bracket: \\([^)]+\\) . +之后的符号使其非贪婪: \\(.+?\\)或者,匹配除结束括号之外的任何字符: \\([^)]+\\)

Both of these regular expressions should do what you need. 这两个正则表达式都可以满足您的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM