如何检测另一个字符串中1个字符串中是否存在子字符串?

时间:2016-10-12 22:27:37

标签: ruby string string-matching

假设我有一个字符串"rubinassociatespa",我想要做的是检测该字符串中包含3个字符或更多字符串的任何子字符串,以及任何其他字符串。

例如,应检测以下字符串:

  • rubin
  • associates
  • spa
  • ass
  • rub

但是不应该检测到的是以下字符串:

  • rob
  • cpa
  • dea
  • ru 或者我的原始字符串中没有出现的任何其他子字符串,或者短于3个字符。

基本上,我有一个字符串,我正在比较许多其他字符串,我只想匹配构成原始字符串的子字符串的字符串。

我希望这很清楚。

3 个答案:

答案 0 :(得分:4)

str = "rubinassociatespa"

arr = %w| rubin associates spa ass rub rob cpa dea ru |
  #=> ["rubin", "associates", "spa", "ass", "rub", "rob", "cpa", "dea", "ru"]

只需使用String#include?

def substring?(str, s)
  (s.size >= 3) ? str.include?(s) : false
end

arr.each { |s| puts "#{s}: #{substring? str, s}" }
  # rubin: true
  # associates: true
  # spa: true
  # ass: true
  # rub: true
  # rob: false
  # cpa: false
  # dea: false
  # ru: false

答案 1 :(得分:2)

您可以使用match

str = "rubinassociatespa"

test_str = "associates"

str.match(test_str) #=> #<MatchData "associates">
str.match(test_str).to_s #=> "associates"

test_str = 'rob'

str.match(test_str) #=> nil

因此,如果test_strstr的子字符串,则match方法将返回整个test_str,否则,它将返回nil

if test_str.length >= 3 && str.match(test_str)
  # do stuff here. 
end

答案 2 :(得分:1)

首先,您需要一个可接受的字符串列表。像https://github.com/first20hours/google-10000-english之类的东西可能会有用。

其次,您需要一种允许快速查找以查看单词是否有效的数据结构。我会为此使用Bloom Filter。如果您不想自己实施,宝石可能会有用:https://github.com/igrigorik/bloomfilter-rb

然后,您需要使用有效单词列表中所有有效单词的列表启动Bloom过滤器。

然后,对于字符串中的每个子字符串,您希望在bloom过滤器结构中进行查找,以查看它是否在有效单词列表中。请参阅此示例,了解如何获取所有子字符串:What is the best way to split a string to get all the substrings by Ruby?

如果bloom过滤器返回true,则需要进行二次检查以确认它实际上在列表中,因为Bloom过滤器是概率数据结构。您可能需要使用数据库来存储有效的单词列表集合,因此您可以只进行数据库查找以确认它是否有效。

我希望这可以让您了解如何继续。