简体   繁体   English

Ruby - 用另一个字符串替换第一次出现的子字符串

[英]Ruby - replace the first occurrence of a substring with another string

a = "foobarfoobarhmm"

I want the output as `"fooBARfoobarhmm" 我希望输出为“fooBARfoobarhmm”

ie only the first occurrence of "bar" should be replaced with "BAR". 即只有第一次出现的“bar”应该用“BAR”代替。

使用#sub

a.sub('bar', "BAR")

String#sub is what you need, as Yossi already said. 正如Yossi所说, String#sub就是你所需要的。 But I'd use a Regexp instead, since it's faster: 但我会使用Regexp,因为它更快:

a = 'foobarfoobarhmm'
output = a.sub(/foo/, 'BAR')

to replace the first occurrence, just do this: 要替换第一个匹配项,只需执行以下操作:

str = "Hello World"
str['Hello'] = 'Goodbye'
# the result is 'Goodbye World'

you can even use regular expressions: 你甚至可以使用正则表达式:

str = "I have 20 dollars"
str[/\d+/] = 500.to_s
# will give 'I have 500 dollars'

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

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