【发布时间】:2016-12-09 03:11:39
【问题描述】:
好的,所以我尝试使用带有正则表达式的 gsub 来仅替换整个单词,而不是其中的一部分。规则之一是将“be”更改为b。但我只想为单个单词做。
原字符串:I really want to be the best at everything
修改后的字符串:I really want to be the best at everything
所需字符串:I really want to b the best at everything
以下代码将接受一个字符串数组,并应将“be”更改为“b”。
array = [
"Hey guys, can anyone teach me how to be cool?
I really want to be the best at everything,
you know what I mean? Tweeting is super fun you guys!!!!",
"OMG you guys, you won't believe how sweet my kitten is.
My kitten is like super cuddly and too cute to be believed right?",
"I'm running out of example tweets for you guys, which is weird,
because I'm a writer and this is just writing and I tweet all day.
For real, you guys. For real.",
"GUISEEEEE this is so fun! I'm tweeting for you guys and this tweet is
SOOOO long it's gonna be way more than you would think twitter can handle,
so shorten it up you know what I mean? I just can never tell how long to keep typing!",
"New game. Middle aged tweet followed by #youngPeopleHashTag Example:
Gotta get my colonoscopy and mammogram soon. Prevention is key! #swag"
]
rules = {
"hello" => "hi",
"too" => "2",
"to" => "2",
"two" => "2",
"for" => "4",
"four" => "4",
"be" => "b",
"you" => "u",
"at" => "@",
"and" => "&"
}
def substitutor(strings,subs)
strings.each_with_index do |string,index|
subs.each do |word,substitute|
strings[index].gsub!(/\bword\b/, substitute)
end
end
end
substitutor(array,rules)
如果我在不使用正则表达式的情况下进行替换,它会给我这个:I really want to b the bst at everything
【问题讨论】:
-
方法的形参错误。是
string,但根据方法定义应该是strings(复数)。 -
您当前的正则表达式(在单词的任一侧查找单词边界)看起来是正确的。请显示您实际用于生成输出的确切代码。
-
Regexp.union是你的朋友。替代方法:在空格上拆分成单词并单独重新映射,join回到单个字符串。 -
另外,您的正则表达式不会插入变量
word,它包含文字字符串 word。