如何将字符串与第一个逗号(如果存在)与Ruby regexp匹配

bra*_*rad 7 ruby regex

我正在努力获得一个regexp(在Ruby中),它将提供以下内容

"one, two" -> "one"
"one, two, three" -> "one"
"one two three" -> "one two three"
Run Code Online (Sandbox Code Playgroud)

我希望匹配任何字符直到字符串中的第一个逗号.如果没有逗号,我希望整个字符串匹配.到目前为止,我的最大努力是

/.*(?=,)?/
Run Code Online (Sandbox Code Playgroud)

这从以上示例产生以下输出

"one, two" -> "one"
"one, two, three" -> "one, two"
"one two three" -> "one two three"
Run Code Online (Sandbox Code Playgroud)

关闭但没有雪茄.有人可以帮忙吗?

Tel*_*hus 16

我想知道它是否可以更简单:

/([^,]+)/
Run Code Online (Sandbox Code Playgroud)

  • 尝试“(.*?),”在当前行中查找 (3认同)

Mar*_*mas 15

必须是正则表达式吗?另一种方案:

text.split(',').first
Run Code Online (Sandbox Code Playgroud)

  • 不一定是-但我“希望”成为 (2认同)
  • @brad为了它的价值,你不应该养成认为所有字符串问题都需要正则表达式的习惯.您可以通过其他方式处理大量案例. (2认同)

pba*_*ann 9

从开始工作只匹配非逗号吗?例如:

/^[^,]+/
Run Code Online (Sandbox Code Playgroud)