Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Regex Match Between "foo" and "bar"

Tags:

regex

ruby

I have unfortunately wandered into a situation where I need regex using Ruby. Basically I want to match this string after the underscore and before the first parentheses. So the end result would be 'table salt'.

_____ table salt (1)   [F]

As usual I tried to fight this battle on my own and with rubular.com. I got the first part

^_____ (Match the beginning of the string with underscores ).

Then I got bolder,

^_____(.*?) ( Do the first part of the match, then give me any amount of words and letters after it )

Regex had had enough and put an end to that nonsense and crapped out. So I was wondering if anyone on stackoverflow knew or would have any hints on how to say my goal to the Ruby Regex parser.

EDIT: Thanks everyone, this is the pattern I ended up using after creating it with rubular.

ingredientNameRegex = /^_+([^(]*)/;

Everything got better once I took a deep breath, and thought about what I was trying to say.

like image 555
Black Dynamite Avatar asked Mar 03 '26 13:03

Black Dynamite


2 Answers

str = "_____ table salt (1)   [F]"
p str[ /_{3}\s(.+?)\s+\(/, 1 ]
#=> "table salt"

That says:

  • Find at least three underscores
  • and a whitespace character (\s)
  • and then one or more (+) of any character (.), but as little as possible (?), up until you find
  • one or more whitespace characters,
  • and then a literal (

The parens in the middle save that bit, and the 1 pulls it out.

like image 196
Phrogz Avatar answered Mar 06 '26 02:03

Phrogz


Try this: ^[_]+([^(]*)\(

It will match lines starting with one or more underscores followed by anything not equal to an opening bracket: http://rubular.com/r/vthpGpVr4y

like image 23
James Shuttler Avatar answered Mar 06 '26 01:03

James Shuttler