-2

How do I reference match 2 and match 3 of a regexp?

http://rubular.com/r/faAwIE98uz

I know I can reference several match groups with $1 and $2 and so on, but I want to reference just the matches of a single group.

--update--

I want to use this regexp (\d{1,3}) with the input 123456789 and reference these matches:

Match 1

  1. 123

Match 2

  1. 456

Match 3

  1. 789
Magne
  • 16,401
  • 10
  • 68
  • 88
  • Can you clarify your question? Can you post your example here, and then show which matches/parts you want to reference? – Reinstate Monica -- notmaynard Nov 19 '13 at 20:02
  • 1
    Use this `"123456789".scan(/(.{1,3})/) # => [["123"], ["456"], ["789"]]`. Now you have an array,and you can access the elements as you wish. – Arup Rakshit Nov 19 '13 at 20:07
  • 1
    thanks for the ruby answer @ArupRakshit ! do you have one for javascript as well? – Magne Nov 19 '13 at 20:12
  • 1
    @Magne http://stackoverflow.com/questions/13895373/javascript-equivalent-of-rubys-stringscan – Mark Thomas Nov 19 '13 at 20:15
  • @MarkThomas Thanks! So `"123456789".match("(\d{1,3})")` is the method, and I get an array from it, so I can get the second and third match from there. Solves my problem. Do you want to add an answer so I can accept it? – Magne Nov 19 '13 at 20:34

1 Answers1

1

In Javascript, you can use the g modifier on the match method:

var matches_array = str.match(/\d{1,3}/g);

Then you can pick the items you want from the array.

Mark Thomas
  • 37,131
  • 11
  • 74
  • 101