简体   繁体   中英

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

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 )) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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