加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 03:08:03 所属栏目:百科 来源:网络整理
导读:我有一段文字,并希望只有 Ruby子这个词的第一个正则表达式匹配.如果我只需要匹配一个字符串,那就没问题了,但是我将多个正则表达式传递给了我的子字符串: regex = Regexp.new(["Lebron James","Chris Paul"].join("|"))names_hash = {"Lebron James" = "**Le
我有一段文字,并希望只有 Ruby子这个词的第一个正则表达式匹配.如果我只需要匹配一个字符串,那就没问题了,但是我将多个正则表达式传递给了我的子字符串:

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.”

我的问题:

我如何设置我拥有的东西,以便我可以取代勒布朗詹姆斯和克里斯保罗的第一个例子,但不是勒布朗詹姆斯的第二个参考?我的预期结果:

“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" => "**Chris Paul**"}
str = "of the best players left in the playoffs,has been to seven straight NBA finals."


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

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

请注意,此方法会改变原始的names_hash – 因此,如果稍后需要该变量,您可能需要事先将其复制.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读