繁体   English   中英

Ruby正则表达式查找并替换字符串中的数字

[英]Ruby regex find and replace a number inside a string

当'49'是一个未知ID时,如何在Rails上使用ruby来查找和替换'49'?

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

寻找正确的语法和示例。 谢谢。

使用字符串的副本可以正常工作:

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

或者,如果您喜欢就地进行操作(直接修改字符串)

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

伊恩。

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

或使用自动更新版本:

str.gsub!(/49/, replacement_id)

另外,请查看Rubular ,它可以让您测试正则表达式。

暂无
暂无

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

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