简体   繁体   中英

Ruby regex find and replace a number inside a string

How would I find and replace '49' when '49' will be an unknown id, using ruby on rails?

str = "select * from clients where client_id = 49 order by registration_date asc"
str = str.gsub(/someRegExThatFinds49/, replacement_id) # <------ Here's the concept

Looking for a syntax and example that's correct. Thanks.

This would work, using a copy of the string:

new_str = str.gsub(/\d+/, replacement_id)

Or, if you prefer to do it in place (modifying the string directly)

str.gsub!(/\d+/, replacement_id)

ian.

unknown_id = 49
puts "hello4849gone".gsub(/#{unknown_id}/, "HERE") #=> hello48HEREgone
str = str.gsub(/49/, replacement_id)

Or use the self-updating version:

str.gsub!(/49/, replacement_id)

Also, check out Rubular which allows you to test out regular expressions.

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