Ruby - 如果实例不匹配,则替换字符串中的单词 [英] Ruby - replace words in a string if instances do not match

查看:58
本文介绍了Ruby - 如果实例不匹配,则替换字符串中的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一次在 Stackvoverflow 上,所以希望我能正确地发布这个 &尽可能清楚.如果需要,请随时将其拆开,让我知道如何在未来发布更清晰的问题.

First time on Stackvoverflow so hope I am posting this correctly & as clear as possible. Please feel free to rip this apart and let me know how to post clearer questions in the future if need be.

Ruby 新手,尽我所能练习.

Newbie to Ruby here and practising where I can.

我想知道如何在 ruby​​ 中替换字符串中的实例.

I want to know how to replace instances in a string in ruby.

例如:

说我有:

string = 'richard julie richard julie sam letty sam letty'

我将如何替换字符串中不等于 'richard' 或 'julie' & 的任何实例再次替换为richard这个词?

How would I replace any instance in the string, that does not equal 'richard' or 'julie' & replace with the word richard again?

因此在实现上述 ruby​​ 方法后将读取新字符串:

so the new string would read after said ruby method was implemented:

string = 'richard julie richard julie richard richard richard richard

我试过像这样使用 gsub:

I have tried using gsub like so:

def string_replace(str)
  if str.include?("sam" || "letty")
    str.gsub! "sam" && "letty", "richard"
  end
end

我已经意识到这种尝试存在很多问题;

I already realise there are a lot of problems with this attempt;

  1. 当使用布尔运算符时,只计算一个参数!任何人都可以解释为什么?这也意味着当我同时需要sam"和sam"时,只替换一个词.'letty' 替换为 'richard'.

  1. When using the boolean operators only one argument is getting evaluated! Could anyone shed any light on why? This also means only one word is being replaces when I need both 'sam' & 'letty' to be replaced for 'richard'.

这种尝试也非常有限,因为它只会替换那些字符串 sam & 的那些实例.莱蒂出现.有没有更好的方法可以覆盖任何不等于richard 或julie 的词,以再次替换为richard 一词?

This attempt is also very limited as it would only replace those instances of those strings sam & letty appearing. Is there a better way that would cover any word that does not equal richard or julie to be replaced for the word richard again?

如果您能对此提供任何帮助,我们将不胜感激.

Any help that could be given on this would be greatly appreciated.

谢谢&新年快乐.

Thank you & happy new year.

P.s 我如何使用反勾号转义,以便我可以打印灰色块来整理它?谢谢

P.s how do I use the back tick escapes so I can print blocks of grey to neaten it up? Thanks

推荐答案

这是一个 gsub,我认为它可以满足您的需求:

This is a gsub that I think will do what you want:

string = 'richard julie richard julie sam letty sam letty'

string.gsub /\b(?!(richard|julie))\w+/, 'richard'

\b断字?!(richard|julie)展望 不是 richard 也不是 julie.所以这基本上是一个分词符和它后面的字母的匹配,这些字母不匹配 richard 也不匹配 julie

\b is a word break and ?!(richard|julie) is a look ahead for not richard nor julie. So this is basically a match for a word break and the letters that follow it, where those letters don't match richard nor julie

这篇关于Ruby - 如果实例不匹配,则替换字符串中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆