开发者

Regex - Match text between 2 characters

I need a regex pattern(s) that will ma开发者_C百科tch on words before a colon and also values between 2 characters. Here's the example, I have a string:

str='`width: 1070px; padding: 0px 10px 0px 10px; height: auto; margin:0px auto 0px auto;`' 

from a stylesheet, I need one array to store the property only (the text before a colon),

(prptyArray[0]='width', prptyArray[1]='padding') 

and another to store the value only (the text between 2 characters)

(valueArray[0]='1070px', valueArray[1]='0px 10px 0px 10px')

Thanks in advance.


([\w-]+):\s*([#\w-\s\d]+);?

Javascript does not have a method for submatch groups. exec only returns the 1st group found. Try exec in the online regular expression tester But still you could get the all the submatches in a fly. Try the following script,

var str = "width: 1070px; padding: 0px 10px 0px 10px; height: auto; margin:0px auto 0px auto;";
var value1 =[];
var value2 =[]; 
var tmp;

do { 
    tmp = str;
    str = str.replace(/([\w-]+):\s*([\#\w-\s\d]+);?/,function($0,$1,$2){
        name1.push($1);
        name2.push($2);
        return $0.replace($1,"").replace($2,"");
    });

} while(tmp!=str);

alert(value1 +"\n"+value2);


something like this in .net

[A-Za-z]+:{1}[A-Za-z0-9 ]+;{1}

If you would like to get access the the property name and values seperately you will have to implement grouping in the expression like the modified expression below. Grouping is implemented with parens "()" around the group or part of expression you would like to capture.

([A-Za-z]+):{1}([A-Za-z0-9 ]+);{1}

Now you will be able to get to the results like this.

myRegex = new Regex("([A-Za-z]+):{1}([A-Za-z0-9 ]+);{1}");

match = myRegex.exec("String you would like to parse");

while (match != null) 
{
    match[0]  // property name: 
    match[1] // values:
}

Enjoy!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜