I want to match a portion of a string using a regular expression and then access that parenthesized substring:
var myString = "something format_abc"; // I want "abc"
var arr = /(?:^|\s)format_(.*?)(?:\s|$)/.exec(myString);
console.log(arr); // Prints: [" format_abc", "abc"] .. so far so good.
console.log(arr[1]); // Prints: undefined (???)
console.log(arr[0]); // Prints: format_undefined (!!!)
What am I doing wrong?
I've discovered that there was nothing wrong with the regular expression code above: the actual string which I was testing against was this:
"date format_%A"
Reporting that "%A" is undefined seems a very strange behaviour, but it is not directly related to this question, so I've opened a new one, Why is a matched substring returning "undefined" in JavaScript?.
The issue was that console.log
takes its parameters like a printf
statement, and since the string I was logging ("%A"
) had a special value, it was trying to find the value of the next parameter.
Using your code:
Edit: Safari 3, if it matters.
Here’s a method you can use to get the nth capturing group for each match:
The
\b
isn't exactly the same thing. (It works on--format_foo/
, but doesn't work onformat_a_b
) But I wanted to show an alternative to your expression, which is fine. Of course, thematch
call is the important thing.Your code works for me (FF3 on Mac) even if I agree with PhiLo that the regex should probably be:
(But, of course, I'm not sure because I don't know the context of the regex.)
In regards to the multi-match parentheses examples above, I was looking for an answer here after not getting what I wanted from:
After looking at the slightly convoluted function calls with while and .push() above, it dawned on me that the problem can be solved very elegantly with mystring.replace() instead (the replacing is NOT the point, and isn't even done, the CLEAN, built-in recursive function call option for the second parameter is!):
After this, I don't think I'm ever going to use .match() for hardly anything ever again.