Ruby正则表达式匹配"foo"和"bar"

Bla*_*ite 2 ruby regex

遗憾的是我徘徊在需要使用Ruby的正则表达式的情况下.基本上我想在下划线之后和第一个括号之前匹配这个字符串.所以最终结果将是"食盐".

_____ table salt (1)   [F]
Run Code Online (Sandbox Code Playgroud)

像往常一样,我试图用自己和rubular.com来对抗这场战斗.我得到了第一部分

^_____ (Match the beginning of the string with underscores ).
Run Code Online (Sandbox Code Playgroud)

然后我变得更大胆,

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

正则表达式已经受够了,并结束了那些废话并将其废弃.所以我想知道stackoverflow上是否有人知道或者对于如何向Ruby Regex解析器说出我的目标有任何暗示.

编辑:谢谢大家,这是我用rubular创建后最终使用的模式.

ingredientNameRegex = /^_+([^(]*)/;
Run Code Online (Sandbox Code Playgroud)

一旦我深呼吸,一切都变得更好,并想到我想说的话.

Phr*_*ogz 7

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

说的是:

  • 找到至少三个下划线
  • 和一个空格字符(\s)
  • 然后是一个或多个(+)任何字符(.),但尽可能少(?),直到找到
  • 一个或多个空白字符,
  • 然后是文字 (

中间的parens保存了那一点,并1把它拉出来.