简体   繁体   中英

RegExp parentheses not capturing

I started messing with javascript a little and have a problem with regular expressions. I have a string...

var example = "top:50px;right:50px;bottom:50px;left:50px;"

I want to extract the '50px' part from the string. 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. I tried the 'g' modifier, but he is not capturing the 50px part. With the 'g' modifier, the result is na array with the entire match...

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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