Andrew
Andrew

Reputation: 2154

JavaScript regexp not matching

I am having a difficult time getting a seemingly simple Regexp. I am trying to grab the last occurrences of word characters between square brackets in a string. My code:

pattern = /\[(\w+)\]/g;
var text = "item[gemstones_attributes][0][shape]";
if (pattern.test(text)) {
    alert(RegExp.lastMatch);
}

The above code is outputting "gemstones_attributes", when I want it to output "shape". Why is this regexp not working, or is there something wrong with my approach to getting the last match? I'm sure that I am making an obvious mistake - regular expressions have never been my string suit.

Edit: There are cases in which the string will not terminate with a right-bracket.

Upvotes: 0

Views: 181

Answers (4)

Dr.Molle
Dr.Molle

Reputation: 117314

Use match() instead of test()


if (text.match(pattern))

test() checks for a match inside a string. This is successfull after the first occurence, so there is no need for further parsing.

Upvotes: 0

retinotop
retinotop

Reputation: 483

i think your problem is in your regex not in your src line .lastMatch.

Your regex returns just the first match of your square brackets and not all matches. You can try to add some groups to your regular expression - and normally you should get all matches.

krikit

Upvotes: 0

dave
dave

Reputation: 4922

RegExp.lastMatch gives the match of the last regular expression. It isn't the last match in the text.

Regular expressions parse left to right and are greedy. So your regexp matches the first '[' it sees and grabs the words between it. When you call lastMatch it gives you the last pattern matched. What you need is to match everything you can first .* and then your pattern.

Upvotes: 1

midgetspy
midgetspy

Reputation: 689

You can greedily match as much as possible before your pattern which will result in your group matching only the last match:

pattern = /.*\[(\w+)\]/g;
var text = "item[gemstones_attributes][0][shape]";
var match = pattern.exec(text);
if (match != null) alert(match[1]);

Upvotes: 2

Related Questions