0

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.

0

4 Answers 4

2

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]);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Thanks for the explanation. This was the first time I have worked with a regexp in JavaScript, so I have no clue how differently they are implemented than the Perl-style regexp.
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.