替换字符串中的单词 - Ruby

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8381499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:33:44  来源:igfitidea点击:

Replace words in a string - Ruby

rubyruby-on-rails-3

提问by Mithun Sasidharan

I have a string in Ruby:

我在 Ruby 中有一个字符串:

sentence = "My name is Robert"

How can I replace any one word in this sentence easily without using complex code or a loop?

如何在不使用复杂代码或循环的情况下轻松替换这句话中的任何一个单词?

采纳答案by Mithun Sasidharan

You can try using this way :

您可以尝试使用这种方式:

sentence ["Robert"] = "Roger"

Then the sentence will become :

那么句子就会变成:

sentence = "My name is Roger" # Robert is replaced with Roger

回答by srcspider

sentence.sub! 'Robert', 'Joe'

Won't cause an exception if the replaced word isn't in the sentence (the []=variant will).

如果被替换的词不在句子中,则不会导致异常([]=变体会)。

How to replace all instances?

如何替换所有实例?

The above replaces only the first instance of "Robert".

以上仅替换了“罗伯特”的第一个实例。

To replace all instances use gsub/gsub!(ie. "global substitution"):

要替换所有实例,请使用gsub/ gsub!(即“全局替换”):

sentence.gsub! 'Robert', 'Joe'

The above will replace all instances of Robert with Joe.

以上将用乔替换罗伯特的所有实例。

回答by Hnatt

If you're dealing with natural language text and need to replace a word, not just part of a string, you have to add a pinch of regular expressions to your gsub as a plain text substitution can lead to disastrous results:

如果您正在处理自然语言文本并且需要替换单词,而不仅仅是字符串的一部分,则必须在 gsub 中添加一些正则表达式,因为纯文本替换可能会导致灾难性的结果:

'mislocated cat, vindicating'.gsub('cat', 'dog')
=> "mislodoged dog, vindidoging"

Regular expressions have word boundaries, such as \bwhich matches start or end of a word. Thus,

正则表达式具有单词边界,例如\b匹配单词的开头或结尾。因此,

'mislocated cat, vindicating'.gsub(/\bcat\b/, 'dog')
=> "mislocated dog, vindicating"

In Ruby, unlike some other languages like Javascript, word boundaries are UTF-8-compatible, so you can use it for languages with non-Latin or extended Latin alphabets:

在 Ruby 中,与 Javascript 等其他一些语言不同,单词边界与 UTF-8 兼容,因此您可以将其用于具有非拉丁字母或扩展拉丁字母的语言:

'с?ль у кис?ль, для вес?ль'.gsub(/\bс?ль\b/, 'цукор')
=> "цукор у кис?ль, для вес?ль"

回答by Sean Hill

First, you don't declare the type in Ruby, so you don't need the first string.

首先,您没有在 Ruby 中声明类型,因此您不需要第一个string.

To replace a word in string, you do: sentence.gsub(/match/, "replacement").

要在字符串替换一句话,你做的:sentence.gsub(/match/, "replacement")