Reputation:
I'm attempting to use Javascript Regex to select something in this fashion: !something: somethingelse;
The exclamation point, the colon, and the semicolon have to be there, but the other parts can be any value. I attempted to do this:
"!test: value; random text here !another: valueagain;".match(/!(.*):(.*);/g);
This returns the original string, !test: value; random text here !another: valueagain;
. Is there something I'm doing incorrectly, or is the Regex incorrect?
Upvotes: 0
Views: 191
Reputation: 342
try this expression :
"!test: value; random text here !another: valueagain;".match(/![^!]*:[^!]*;/g);
return :
["!test: value;", "!another: valueagain;"]
Upvotes: 0
Reputation: 72947
Try this:
.match(/!(.*?):(.*?);/g);
The added questionmarks make the *
non-greedy, meaning it matches a string that's as short as possible.
Upvotes: 0
Reputation: 239643
You are using greedy matchers, use non-greedy matchers like this
"!test: value; random text here !another: valueagain;".match(/!(.*?):(.*?);/g);
# [ '!test: value;', '!another: valueagain;' ]
(.*):
consumes everything till the last :
in the string, as it is greedy. That is why you are getting only a single string. Simply make it non-greedy by using ?
, like this .*?
. This makes sure that it matches till the first :
.
Upvotes: 0
Reputation: 75579
As devnull suggested, use non-greedy quantifiers.
"!test: value; random text here !another: valueagain;".match(/!(.*?):(.*?);/g);
Output:
[ '!test: value;', '!another: valueagain;' ]
In general, regular expression quantifiers like *
are greedy, in the sense that they will try to match as large of an expression as possible.
The non-greedy versions *?
will match only as much as they need to, to match.
Upvotes: 1