4

I wonder why these regexps aren't equivalent:

/(a)(a)(a)/.exec ("aaa").toString () => "aaa,a,a,a" , as expected
/(a){3}/.exec ("aaa").toString ()    => "aaa,a"      :(
/(a)*/.exec ("aaa").toString ()      => "aaa,a"      :(

How must the last two be reformulated so that they behave like the first? The important thing is that I want arbitrary multiples matched and remembered.

The following line

/([abc])*/.exec ("abc").toString () => "abc,c"

suggests that only one character is saved per parenthesis - the last match.

3
  • I was trying to solve this exact problem the other day. There are other topics on this exact issue if you search for them. The short answer is that this is unsupported in JS. :( indeed Commented Mar 6, 2014 at 23:56
  • Can you give an example of where you encountered this problem. Like an example string you want to match and the return you desire. The reason for the difference in the "aaa"'s is simply the fact that there is a different number of capture groups. Commented Mar 6, 2014 at 23:59
  • I simply tried to implement an explode function for strings with regexp and want to experiment further doing syntactical analysis. I circumvented this problem via str.match (/([^ \n\t\(\)]+|\(|\))/g) - this also treats parenthesis as tokens. But I think this isn't the solution of the problem Commented Mar 7, 2014 at 0:29

2 Answers 2

5

You probably are looking for this:

var re = /([abc])/g,
    matches = [],
    input = "abc";
while (match = re.exec(input)) matches.push(match[1]);

console.log(matches);
//=> ["a", "b", "c"] 

Remember that any matching group will give you last matched pattern not all of them.

Sign up to request clarification or add additional context in comments.

5 Comments

This works great if you're only matching (a)(a)(a). If you want to match (a)(b)*(c), you have to cut up the string, which is unfortunate
Thanks! Functionally this is it what I want. I only thought it must be possible - or would be nice - that regexp do it for me. But I fear it must be coded by hand ;)
Yes that's true, this is the best you can get.
Also if it works out can you mark the answer as accepted by clicking on tick mark on top-left of my answer.
This was my second question and first true conversation on stackoverflow :D. I rarely need to ask since here are plenty of good answers. Thanks again!
0

RegExBuddy describes it very well:

Note: you repeated the capturing group itself. The group will capture only the last iteration

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.