def sub_word(str, person, word, replacement)
str.sub(/^(?=.*\b#{person}\b).*\K\b#{word}\b/, replacement)
end
我将展示几个示例,其中字符串的第一行(str)和最后三个参数是固定的,即
f = "Mike likes banana, kiwi and grapes.\n"
person = "Mary"
word = "banana"
replacement = "orange"
写起来很方便
args = ["Mary", "banana", "orange"]
示例中唯一发生变化的是字符串的第二行(包含"Mary")。 所考虑的示例如下。
sub_word(f + "Mary likes banana, apple and melon.", *args)
#=> "Mike likes banana, kiwi and grapes.\nMary likes orange, apple and melon."
sub_word(f + "Mary likes apple, banana and melon.", *args)
#=> "Mike likes banana, kiwi and grapes.\nMary likes apple, orange and melon."
sub_word(f + "Yes, Mary is fond of apple, banana and melon.", *args)
#=> "Mike likes banana, kiwi and grapes.\nYes, Mary is fond of apple, orange and melon."
sub_word(f + "Apple, banana and melon are liked by Mary.", *args)
#=> "Mike likes banana, kiwi and grapes.\nApple, orange and melon are liked by Mary."
sub_word(f + "Mary likes pear, apple and melon.", *args)
#=> "Mike likes banana, kiwi and grapes.\nMary likes pear, apple and melon."
sub_word(f + "Maryann likes banana, apple and melon.", *args)
#=> "Mike likes banana, kiwi and grapes.\nMaryann likes banana, apple and melon."
sub_word(f + "Mary likes bananas, apple and melon.", *args)
#=> "Mike likes banana, kiwi and grapes.\nMary likes bananas, apple and melon."
^ match the beginning of a line
(?= begin a positive lookahead
.* match zero or more characters other than line terminators,
as many as possible
\bMary\b match 'Mary' with word boundaries before and after
) end positive lookahead
.* match zero or more characters other than line terminators,
as many as possible
\K reset the starting point of the reported match and exclude
any previously consumed characters in the final match
\bbanana\b match 'banana' with word boundaries before and after
2条答案
按热度按时间qoefvg9y1#
我们可以构造方法
我将展示几个示例,其中字符串的第一行(
str
)和最后三个参数是固定的,即写起来很方便
示例中唯一发生变化的是字符串的第二行(包含
"Mary"
)。所考虑的示例如下。
在所有示例中,String#sub使用的正则表达式的计算结果如下。
表达式的元素如下。
请注意,positive lookahead Assert字符串
"Mary"
在该行的某个位置。35g0bw712#
您可以使用如下所示的正向后查找
输入
输出
或者不使用正则表达式
“迈克喜欢香蕉、猕猴桃和葡萄。玛丽喜欢香蕉、苹果和西瓜。“
输出