views:

52

answers:

3

given:

var regexp = new RegExp("<~~include(.*?)~~>", "g");

What's the easist way in javascript to assign a variable to whatever's matched by .*?

I can do this, but it's a little ugly:

myString.match(regexp).replace("<~~include", "").replace("~~>", "");
+2  A: 

(Quotes from MDC)

Including parentheses in a regular expression pattern causes the corresponding submatch to be remembered. For example, /a(b)c/ matches the characters 'abc' and remembers 'b'.

Since .*? is the first (and only) remembered match, use $1 in your replacement string:

var foo = myString.replace(regexp, '$1');

Edit: As per your comment, you can also (perhaps with clearer intention) do this:

var foo = regexp.exec(myString)[1];
Matt Ball
Thanks bears. Thing is, I don't actually want to replace the whole thing, I just want to find out what the value of .*? is.
morgancodes
[Nick](http://stackoverflow.com/users/21399/nick) just commented (and then deleted his comment) that the first version will also work. He's correct, but I guess the intention of the `replace` version is less clear than the intention of the `exec` version. In either case, you have to assign the value returned by `replace`/`exec` to another variable.
Matt Ball
+1  A: 

Javascript should return an array object on a regex match, where the zero index of the array is the whole string that was matched and the following indexes are the capture groups. In your case something like:

var myVar = regexp.exec(myString)[1];

should assign the value of the (.*?) capture group to myVar.

eldarerathis
Nope, that won't work. You need to use `exec`, not `match`.
Matt Ball
Yeah, thanks. That was a typo...ninja-fixed it just before your comment posted, though :)
eldarerathis
A: 

Hi morgancodes,

You can use lookahead for part of this regular expression. See here:

http://stackoverflow.com/questions/3392738/regular-expression-for-extracting-a-number/3398423#3398423

and/or here:

http://www.regular-expressions.info/lookaround.html

Skyler
Lookaround is not the answer. How is that supposed to help?
Matt Ball
[quote] Thanks bears. Thing is, I don't actually want to replace the whole thing, I just want to find out what the value of .*? is. – morgancodes 15 mins ago
Skyler
So they could write a regex that [EDIT] matches <~~include(.*?)~~> and excludes the information they do not want.
Skyler