查找字符串和子字符串组合的正则表达式

时间:2014-09-01 18:58:03

标签: ruby regex

我有一个字符串说 字符串= “例如= ABC”。或“eg2 = abc”或eg2 =“abc”。或eg2 =“abc”

现在我有另一个字符串说 substring =“abc。”或“abc”或“abc。”或“abc”

现在我想在string和substring是以下任意组合时返回true。 问题是如何使用正则表达式。

3 个答案:

答案 0 :(得分:1)

您可以使用Regexp和匹配来轻松搜索字符串:

str1 = "abc=def="
str2 = "abc"
!! str1.match(Regexp.compile(Regexp.escape(str2))) #=> true
!! str1.match(Regexp.compile(Regexp.escape("12"))) #=> false

答案 1 :(得分:1)

假设你有数组中的字符串:

strs = ["eg=abc.", "eg2= abc ", 'eg2=" abc."', 'eg2="abc"']
subs = [" abc.", " abc ", "abc. ", "abc"]

然后您可以执行以下操作:

strs.any?{|s| subs.any?{|sub| s.include? sub}}

为简洁起见,这会利用Enumerable#any?String#include?

但如果我们能够更多地了解你真正想做的事情,我无法帮助你思考另一种解决问题的方法。

答案 2 :(得分:0)

不需要正则表达式:只使用字符串#include?方法

您可以使用String#include?方法检查没有正则表达式的检查。例如:

# True if str1 contains str2; otherwise false.
def string_match? str1, str2
    str1.include? str2
end

# Your provided corpus, as a pair of arrays.
str1 = ["eg=abc.", "eg2= abc ", 'eg2=" abc."', 'eg2="abc"']
str2 = [" abc.", " abc ", "abc. ", "abc"]

# Putting the method to use on your sample strings.    
str1.each do |str1|
  str2.each do |str2|
  puts "'#{str1}' includes '#{str2}'" if string_match?(str1, str2)
  end
end

这只是检查第一个数组中的每个字符串与第二个数组中的每个字符串,并报告匹配。如果找到任何两个字符串, #string_match?将返回true,否则返回false。