1

I have some text

I01:00:00:05
I01:00:00:04
I01:00:00:03
I01:00:00:02
I01:00:00:01

Is there a regex that will find each one?

I tried: var locs = txt.match(/(([A-Z]\d\d\:\d\d\:\d\d\:\d\d)+)+/);

And it finds 5 copies of the first pattern that matches.

Is there a way to get an array with each of them in it?

Thanks

3
  • Is this text part of a larger document? What exactly are you trying to match? Commented Mar 7, 2011 at 18:17
  • The regex pattern. but I want to end up with all the matches, not just the first one Commented Mar 7, 2011 at 18:20
  • Write your regular expression to match a single one, instead of trying to match them all in a single expression. Then use the /g flag, as noted by the answers below. Commented Mar 7, 2011 at 18:22

4 Answers 4

2

if you include the 'g' flag at the end it should work.

var locs = txt.match(/(([A-Z]\d\d\:\d\d\:\d\d\:\d\d)+)+/g);
Sign up to request clarification or add additional context in comments.

1 Comment

That did it! Thanks very much. I should have remembered that from my unix days
0

You are simply missing the g flag on your regexp and it will find all the occurences that match the pattern. Like so:

var locs = txt.match(/(([A-Z]\d\d\:\d\d\:\d\d\:\d\d)+)+/g);

of course if that pattern is actually good ;)

Comments

0

Write your regular expression to match a single instance, and use the global specifier /g to get a collection of matches (note the modification to regular expression):

var locs = txt.match(/([A-Z]\d\d\:\d\d\:\d\d\:\d\d)/g);

http://rubular.com/r/L2ZNyz2yJy

Comments

0

Indeed in this case the "+" sign is not necessary:

var locs = txt.match(/[A-Z]\d\d\:\d\d\:\d\d\:\d\d/g);

locs will be ["I01:00:00:05", "I01:00:00:04", "I01:00:00:03", "I01:00:00:02", "I01:00:00:01"] .

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.