gpt4 book ai didi

Ruby 仅替换作为哈希传递的多个正则表达式的第一次出现

转载 作者:数据小太阳 更新时间:2023-10-29 07:27:54 25 4
gpt4 key购买 nike

我有一段文字,只想用 Ruby sub 匹配该词的第一个正则表达式。如果我只需要匹配一个字符串就好了,但是我将多个正则表达式传递到我的子程序中:

regex = Regexp.new(["Lebron James", "Chris Paul"].join("|"))
names_hash = {"Lebron James" => "**Lebron James**", "Chris Paul" => "**Chris Paul**"}

str = "of the best players left in the playoffs, Lebron James is the most experienced player left in the field and probably in all of the league. Chris Paul has played in many playoff games but has never been to a conference final. Lebron James on the other hand, has been to seven straight NBA finals."

如果我运行 str.gsub(regex, names_hash),Lebron James 和 Chris Paul 的所有实例都会被替换为:

"of the best players left in the playoffs, Lebron James is the most experienced player left in the field and probably in all of the league. Chris Paul has played in many playoff games but has never been to a conference final. Lebron James on the other hand, has been to seven straight NBA finals."

如果我运行 str.sub(regex, names_hash)(sub 而不是 gsub),我只会得到 Lebron James 的第一次出现,但不会得到 Chris Paul:

"of the best players left in the playoffs, Lebron James is the most experienced player left in the field and probably in all of the league. Chris Paul has played in many playoff games but has never been to a conference final. Lebron James on the other hand, has been to seven straight NBA finals."

我的问题:

我如何设置我所拥有的,以便我可以替换 Lebron James 和 Chris Paul 的第一个实例,但不能替换 Lebron James 的第二个引用?我的预期结果:

"of the best players left in the playoffs, Lebron James is the most experienced player left in the field and probably in all of the league. Chris Paul has played in many playoff games but has never been to a conference final. Lebron James on the other hand, has been to seven straight NBA finals."

最佳答案

怎么样:

regex = Regexp.new(["Lebron James", "Chris Paul"].join("|"))
names_hash = {"Lebron James" => "**Lebron James**", "Chris Paul" => "**Chris Paul**"}
str = "of the best players left in the playoffs, Lebron James is the most experienced player left in the field and probably in all of the league. Chris Paul has played in many playoff games but has never been to a conference final. Lebron James on the other hand, has been to seven straight NBA finals."


str.gsub(regex) { |name| names_hash.delete(name) || name }

这将从 names_hash 中读取,仅用于第一次替换;之后,gsub 将“默认”不做任何更改。

请注意,此方法会改变原始的 names_hash - 因此如果稍后需要该变量,您可能需要预先 dup 它。

关于Ruby 仅替换作为哈希传递的多个正则表达式的第一次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50492954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com