【问题标题】:Regular expression to match exact substring at the beginning of string正则表达式以匹配字符串开头的确切子字符串
【发布时间】:2016-07-12 22:15:29
【问题描述】:

我有一个子字符串要在源字符串的开头完全匹配。

source_string = "This is mat. This is cat."

substring1 = "This is"

substring2  = "That is"

source_string.match(/^(#{substring1}|#{substring2})$/)

这是我尝试过的,它应该像这样工作,如果确切的 'This is' 或 'That is' 出现在字符串的开头,它应该匹配,不管@中的那些子字符串后面是什么987654324@。即使存在'This is',我的代码也会给出nil。

【问题讨论】:

    标签: ruby regex ruby-on-rails-4


    【解决方案1】:

    删除正则表达式模式末尾的$。

    source_string.match(/^(#{substring1}|#{substring2})$/)
                                                       ↑
    

    通过附加$,它要求模式以This is 或That is 结尾。开头只需要^。


    source_string = "This is mat. This is cat."
    substring1 = "This is"
    substring2  = "That is"
    source_string.match(/^(#{substring1}|#{substring2})/)
    # => #<MatchData "This is" 1:"This is">
    

    【讨论】:

    • 哦,好的,谢谢它的工作我不知道 $ 的用途 :)
    【解决方案2】:

    虽然@falsetru 对核心问题的看法是正确的,但正则表达式实际上仍然是错误的。虽然目标是匹配模式在源字符串的开头,而不是在每行的开头,但应该使用\A 修饰符(参见Regexp::Anchors详情):

    source_string = <<-STR
    Not to be matched. 
    This is cat.
    STR
    source_string.match(/^This is/) # this should not be matched!
    #⇒ #<MatchData "This is">
    source_string.match(/\AThis is/)
    #⇒ nil
    

    【讨论】:

      【解决方案3】:

      我不会使用正则表达式:

      [substring1, substring2].any? { |sub| source_string.start_with?(sub) }
        #=> true
      

      【讨论】:

      • 是的,那个。我个人非常喜欢正则表达式,以至于我的代码总是受到它的影响:)
      猜你喜欢
      • 2022-08-03
      • 2014-08-15
      • 2015-12-11
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 2016-12-07
      • 1970-01-01
      • 2011-11-08
      相关资源
      最近更新 更多