【问题标题】:How do I detect the presence of a substring in 1 string in another string?如何检测另一个字符串中的一个字符串中是否存在子字符串?
【发布时间】:2017-02-21 21:25:17
【问题描述】:

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

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

  • rubin
  • associates
  • spa
  • ass
  • rub 等

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

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

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

我希望这很清楚。

【问题讨论】:

    标签: ruby string string-matching


    【解决方案1】:
    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
    

    【讨论】:

    • 这是一个很好的答案,但我想补充一点,如果你想返回一个匹配的数组,你可以像这样使用select:arr.select { |s| substring?(str, s) }
    • 将每个字符串转换为正则表达式有什么好处?
    • @Stefan,没有任何好处。你为什么要问? ¯\_(ツ)_/¯
    【解决方案2】:

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

    其次,您需要一个允许快速查找以查看单词是否有效的数据结构。我会为此使用布隆过滤器。如果您不想自己实现它,这个 gem 可能会很有用:https://github.com/igrigorik/bloomfilter-rb

    然后您需要使用有效词列表中所有有效词的列表来启动布隆过滤器。

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

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

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

    【讨论】:

      【解决方案3】:

      你可以使用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_str 是str 的子字符串,那么match 方法将返回整个test_str,否则,它将返回nil。

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

      【讨论】:

      • match 将其参数视为正则表达式。对于纯字符串,include? 就足够了。
      猜你喜欢
      • 1970-01-01
      • 2013-05-12
      • 2019-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-07
      • 2011-03-24
      相关资源
      最近更新 更多