0

I'd love to extract multiple matches from one block of text using regex in Ruby.

Here's an example;

https://rubular.com/r/l2Mi2xmahACmsV enter image description here

The regex caught two matches in the example.

  • host: test01.com
  • service: 000001

The regex seems okay, so now I will apply with Ruby.

--
[5] pry(main)> t.match(/Service\|(?<service>\d*)\|/)[:service]
=> "000001"

[6] pry(main)> t.match(/Hostname\|(?<host>[^|]*|)/)[:host]
=> "test01.com"
--

It's running and it's totally expected with single match, but how about multiple matches?

[7] pry(main)> t.match(/Hostname\|(?<host>[^|]*)\||Service\|(?<service>\d*)\|/)
=> #<MatchData "Service|000001|" host:nil service:"000001">

It seems that It does not work. (host:nil)

Any ideas to extract multiple matches in Ruby?

Toshi
  • 6,012
  • 8
  • 35
  • 58
  • 1
    Use the `.scan` method – Wiktor Stribiżew Mar 14 '19 at 14:58
  • @WiktorStribiżew, I am sure you will be the first to agree that the use of `scan` can be problematic when the regular expression contains capture groups. Here's an example. Suppose `str = "a1ab2cd3d"` and we wish to find all digits that are preceded and followed by the same letter (`["1", "3"]`). We could use the regex `r = /(?<=(\p{Alpha}))\d(?=\1)/`. Then `str.scan(r) #=> [["a"], ["d"]]`. We can, however, obtain the desired result as follows: `str.gsub(r).to_a #=> ["1", "3"]`. – Cary Swoveland Mar 14 '19 at 17:02

0 Answers0