简体   繁体   English

如何创建一个正则表达式,通过ruby的gsub替换字符串中的所有匹配项?

[英]How to create a regular expression that replaces all matches in a string through ruby's gsub?

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 以上将正确地给我: aeaeaeaeae

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! 非常感谢!

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 )) . 所以问题不在于正则表达式替换了一次,而是它与字符串的一部分相匹配 - 从第一个((到最后一个))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM