ruby-on-rails - 如何删除与数组的任何元素匹配的子字符串

标签 ruby-on-rails ruby arrays string

我有:

str ="this is the string "

我有一个字符串数组:

array =["this is" ,"second element", "third element"]

我想处理字符串,以便删除与数组的任何元素匹配的子字符串,并返回字符串的其余部分。我想要以下输出:

output: "the string "

我该怎么做?

最佳答案

您没有说您是想要真正的子串匹配,还是在字边界处进行子串匹配。这是有区别的。以下是遵守单词边界的方法:

str = "this is the string "
array = ["this is" ,"second element", "third element"]
pattern = /\b(?:#{ Regexp.union(array).source })\b/ # => /\b(?:this\ is|second\ element|third\ element)\b/

str[pattern] # => "this is"
str.gsub(pattern, '').squeeze(' ').strip # => "the string"

这是 unionunion.source 发生的事情:

Regexp.union(array) # => /this\ is|second\ element|third\ element/
Regexp.union(array).source # => "this\\ is|second\\ element|third\\ element"

source 以一种形式返回连接数组,Regex 在创建模式时可以更轻松地使用这种形式,而不会在模式中注入(inject)漏洞。考虑这些差异以及它们在模式匹配中可以做什么:

/#{ Regexp.union(%w[a . b]) }/ # => /(?-mix:a|\.|b)/
/#{ Regexp.union(%w[a . b]).source }/ # => /a|\.|b/

第一个创建一个单独的模式,它有自己的大小写标志、多行和空格标记,将嵌入外部模式中。这可能是一个很难追踪和修复的错误,所以只有在您打算拥有子模式时才这样做。

另外,请注意如果您尝试使用会发生什么:

/#{ %w[a . b].join('|') }/ # => /a|.|b/

生成的模式中嵌入了通配符 .,这会破坏您的模式,使其匹配任何内容。不要去那里。

如果我们不告诉正则表达式引擎遵守单词边界,那么可能会发生意想不到的/不希望的/可怕的事情:

str = "this isn't the string "
array = ["this is" ,"second element", "third element"]
pattern = /(?:#{ Regexp.union(array).source })/ # => /(?:this\ is|second\ element|third\ element)/

str[pattern] # => "this is"
str.gsub(pattern, '').squeeze(' ').strip # => "n't the string"

在处理包含完整单词的子字符串时,从单词的角度来思考很重要。引擎不知道其中的区别,所以你必须告诉它该做什么。不必进行文本处理的人经常会错过这种情况。

关于ruby-on-rails - 如何删除与数组的任何元素匹配的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23700784/

相关文章:

ruby-on-rails - Prawn :锚定文本中间到给定点

arrays - 在 Octave/Matlab 中类型转换为 int

ruby-on-rails - Rails_admin,用另一个字段的值更改一个字段的值

javascript - 将 json 对象作为 'payload' 传递给 db -rails postgres

ruby-on-rails - 启动瘦服务器时加载 bootstrap-sass 时出现问题,rails

ruby - 无方法错误 : undefined method `[]=' for nil:NilClass

sql - rails - 如何从另一个查询中减去一个查询?

ruby - 使用 Ruby 编辑 XML

php - PHP 函数可能未定义的参数

javascript - 将单词和定义列表拆分为两个数组