[英]RegExp parentheses not capturing
I started messing with javascript a little and have a problem with regular expressions. 我开始弄乱javascript并遇到了正则表达式问题。 I have a string...
我有一串...
var example = "top:50px;right:50px;bottom:50px;left:50px;"
I want to extract the '50px' part from the string. 我想从字符串中提取“ 50px”部分。 I tried it with this code...
我尝试使用此代码...
var theMatch = example.match(new RegExp('[a-zA-Z]+:([0-9]+px);'));
which extracts the 50px portion but only for the first occurence of the searched value in the string. 它提取50px部分,但仅用于字符串中搜索值的首次出现。 I tried the 'g' modifier, but he is not capturing the 50px part.
我尝试了'g'修饰符,但他没有捕捉到50px的部分。 With the 'g' modifier, the result is na array with the entire match...
使用'g'修饰符,结果是具有整个匹配项的na数组...
top:50px
right:50px
... etc ...
Is there a one line solution for this or i have to do another reg match? 是否为此提供一种解决方案,或者我必须进行另一项匹配? Also, are there any strange behaviour that involves the modifiers and the parenthesis that I am not aware of?
此外,是否有我不知道的涉及修饰符和括号的奇怪行为?
You need to iteratively reapply the regex: 您需要迭代地重新应用正则表达式:
var myregexp = /[a-zA-Z]+:([0-9]+px);/g;
var match = myregexp.exec(subject);
while (match != null) {
for (var i = 0; i < match.length; i++) {
// matched text: match[i], so match[1] contains e.g. "50px"
}
match = myregexp.exec(subject);
}
Here is a solution which works for values that does not contain :
and ;
这里是一个适用于不包含价值的解决方案
:
和;
: :
var s = 'top:50px;right:50px;bottom:50px;left:50px;';
s.match(/[^:;]+(?=;|$)/g);
The following one is based on keys : 以下基于密钥:
var s = 'top:50px;right:50px;bottom:50px;left:50px;';
s.replace(/[ ;]+$/, '').split(/(?:^| *;).*?: */).slice(1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.