0

I need a regex pattern(s) that will match 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.

2 Answers 2

1

([\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);
1
  • Thanks unigg, it works perfectly although I believe you're using the wrong array names inside your function so once I changed it to value1, value2 respectively, it worked!
    – user356808
    Jun 3, 2010 at 15:10
0

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!

4
  • 3
    {1} clutters the expression and can be omitted.
    – Bart Kiers
    Jun 2, 2010 at 19:38
  • Thanks for the quick answer Doug. In response to your answer, do you know how I would be able to use the split method to get an array of properties or an array of values? i.e. str.split(/^[A-z]+:/);?
    – user356808
    Jun 2, 2010 at 19:48
  • This was definitely closer to what I was looking for although I was only getting the first group that it matched.
    – user356808
    Jun 3, 2010 at 15:15
  • I think the fix is to put one more grouping expression around the entire expresson like this (([A-Za-z]+):{1}([A-Za-z0-9 ]+);{1})
    – Doug
    Jun 3, 2010 at 15:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.