如何创建一个正则表达式,通过 ruby 的 gsub 替换字符串中的所有匹配项?
我想知道为什么我的正则表达式不起作用,我需要实现以下行为:
"aoaoaoaoaoao".gsub!(/o/, 'e')
上面将正确地给出: aeaeaeaeaeae
现在,真实的东西看起来像这样:
"Today I ate a ((noun)), and it tasted ((adjective))".gsub!(/\(\(.*\)\)/, "word")
它的结果是: “今天我吃了一个字”,但我希望它能回到我身边: “今天我吃了一个单词,它尝到了单词的味道”
很明显我的正则表达式有问题,(对吗?)因为它只会替换一次。你们能告诉我如何让它取代所有比赛吗? (就像我的第一个例子)
非常感谢!
I wonder why my regular expression will not work, I require to achieve the following behavior:
"aoaoaoaoaoao".gsub!(/o/, 'e')
The above will correctly give me: aeaeaeaeaeae
Now, The real thing looks like this:
"Today I ate a ((noun)), and it tasted ((adjective))".gsub!(/\(\(.*\)\)/, "word")
And its result is: "Today I ate a word", But I had hoped It'd return to me:
"Today I ate a word, and it tasted word"
It's obvious there's problem with my regular expression, (right?) because it'll only replace once. Could you guys please tell me how to make it replace all matches? (like in my first example)
Thank very much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要以下正则表达式:
.*?
使用尽可能少的字符来获得匹配项。因此,问题不在于正则表达式替换了一次,而是它匹配了字符串的太大部分 - 从第一个((
到最后一个))
。You need the following regex:
.*?
consumes as little characters as possible to obtain a match. So the problem was not that the regex replaced once but that it matched too large a part of the string - from the first((
to the last))
.