【问题标题】:Ruby, checking if an item exists in an array using Regular expressionRuby,使用正则表达式检查数组中是否存在项目
【发布时间】:2021-03-19 22:04:57
【问题描述】:

我正在尝试搜索字符串数组 (new_string) 并检查它是否包含任何“运算符”

我哪里错了?

def example
  operators = ["+", "-"]
  string = "+ hi"
  new_string = string.split(" ")
  if new_string.include? Regexp.union(operators)
    print "true"
  else
    print "false"
  end
end

【问题讨论】:

  • 你在问一个strings数组是否包含一个特定的regexp。显然,这总是错误的,因为您的数组包含正则表达式,它包含字符串。

标签: regex ruby


【解决方案1】:

您可以改用any?,它采用模式

pattern = Regexp.union(['+', '-']) #=> /\+|\-/

['foo', '+', 'bar'].any?(pattern) #=> true

但既然你已经有了一个字符串,你可以跳过拆分并使用match?

'foo + bar'.match?(pattern) #=> true

【讨论】:

    【解决方案2】:

    您希望确定字符串 (string) 是否包含给定字符数组 (operators) 中的至少一个字符。这些字符是'+''-' 的事实是不相关的;相同的方法将用于任何字符数组。有很多方法可以做到这一点。 @Stefan 给了一个。这里还有一些。他们都没有变异(修改)string

    string = "There is a + in this string"
    operators = ["+", "-"]
    

    以下用于一些计算。

    op_str = operators.join
      #=> "+-"
    

    #1

    r = /[#{ op_str }]/
      #=> /[+-]/ 
    string.match?(r)
      #=> true 
    

    [+-] 是一个字符类。它断言字符串匹配类中的任何字符。

    #2

    string.delete(op_str).size < string.size
      #=> true
    

    String#delete

    #3

    string.tr(op_str, '').size < string.size
      #=> true
    

    String#tr

    #4

    string.count(op_str) > 0
      #=> true 
    

    String#count

    #5

    (string.chars & operators).any?
      #=> true 
    

    Array#&

    【讨论】:

      猜你喜欢
      • 2016-11-08
      • 2020-08-06
      • 2018-12-12
      • 2014-10-03
      • 1970-01-01
      • 1970-01-01
      • 2013-04-29
      • 1970-01-01
      相关资源
      最近更新 更多