Reputation: 1345
I want a regex that match all the occurrences in a string of a certain patter:
\d+
My string is a CSS rule, so I know that it starts with a property and should end with a semicolon. I want to get what is in the middle.
For example, in the string:
margin: 0px 3px 2px;
I wish to get:
0px 3px 2px
I'm trying something like:
margin:\s*?(\d+)px
but it matches only the first. Then I don't know how to say that after the digit, can be two characters (em|px), just one (%) or nothing at all.
Any regex guru can helps me?
I preferred to open a new question, but this post is related to my previuos here: CSS Regular Expression
Upvotes: 0
Views: 337
Reputation: 16961
How about:
// returns array: ["0px", "3px", "2px"]
"margin: 0px 3px 2px;".match(/\d+(?:px|em)?/g)
Use g
(global) flag, to match against whole string instead of stopping at first match.
// other example - returns array: ["3em", "2px", "39"]
"margin: 3em 2px 39;".match(/\d+(?:px|em)?/g)
To further clarify how this works:
\d+
matches numbers (one or more following each other)(?:px|em)?
skips capturing (but still matches!) this group - looks for px or em strings. Question mark at the end means that this whole group may not be found (for when there are numbers without units).Edit: To answer OP concerns from the comment below.
Doing this: new RegExp(/\d+(?:px|em)?/g).exex(mystring)
doesn't work because of two reasons.
First - you can't provide flags (g
) when creating new RegExp from another (which is the case here - /\d+(?:px|em)?/g
is equivalent of RegExp object, just like []
is equivalent of new Array()
. Correct way of creating RegExp object using new RegExp
construct is passing two string arguments. First is pattern, second are flags. So it above would become: new RegExp('\d+(?:px|em)?', 'g')
.
Second thing is that .exec()
method always returns first match (not all) so it won't work for what you're after.
So, to reuse that regular expression in couple of places in your script you would have to assign it to variable, and then pass to .match()
function. It could look like this:
var reg = new RegExp('\d+(?:px|em)?', 'g');
// somewhere down the road...
mystring.match(reg);
// and on some other string...
myotherstring.match(reg);
Upvotes: 1
Reputation: 577
Maybe you need this :
var re = /^\w+:(.+);$/;
var st = "margin: 0px 3px 3px;";
re.exec(st);
or fiddle about with it in Regex Tester. Keep the website in your favorites for future uses
Upvotes: 0
Reputation: 15200
I think instead of margin:\s*?(\d+)px
you should try margin:.*?;
with back reference something like
margin:(.*?);
Upvotes: 0