Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby regex extract words between { | | }

Tags:

regex

ruby

How can I get the individual words contained within {} out of the text

an example of the text {Creating|Making|Producing} blah blah blah

I have got this far with my limited regex knowledge

text.scan(/{([^}]*)}/)

This just gives me {Creating|Making|Producing} but I want Creating Making Producing

Thank you!

like image 313
Max Rose-Collins Avatar asked May 31 '26 15:05

Max Rose-Collins


2 Answers

You could split the found match.

text.scan(/{([^}]*)}/)[0][0].split('|')

An easier regex could be:

text.scan(/{(.*?)}/)

Explanation:

  • { - a { character
  • .*?} - anything (.*) until the first (?) } character is encountered
like image 132
rid Avatar answered Jun 03 '26 11:06

rid


Another one :

s = 'an example of the text {Creating|Making|Producing} blah blah blah'
s.scan(/(?<=[|{])[A-Za-z]+(?=[}|])/)
# => ["Creating", "Making", "Producing"]

(?<=pat) :

Positive lookbehind assertion: ensures that the preceding characters match pat, but doesn't include those characters in the matched text

(?=pat) :

Positive lookahead assertion: ensures that the following characters match pat, but doesn't include those characters in the matched text

Look in Rubular also.

Update As per the comment of @Mike Campbell .

s = 'an example of the text {Creating|Making|Producing} blah {foo} blah |bla|'
s.scan(/(?<={)[a-z|]+(?=})/i).flat_map { |m| m.split("|") }
# => ["Creating", "Making", "Producing", "foo"]

Again see the Rubular.

like image 32
Arup Rakshit Avatar answered Jun 03 '26 10:06

Arup Rakshit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!