代码之家  ›  专栏  ›  技术社区  ›  Daniel Beardsley

返回Ruby正则表达式的第一个匹配项

  •  87
  • Daniel Beardsley  · 技术社区  · 16 年前

    我正在寻找一种在Ruby中对字符串执行正则表达式匹配并在第一次匹配时使其短路的方法。

    我正在处理的字符串很长,看起来像是标准方式( match 方法)将处理整个过程,收集每个匹配项,并返回包含所有匹配项的MatchData对象。

    match = string.match(/regex/)[0].to_s
    
    5 回复  |  直到 16 年前
        1
  •  151
  •   Sebastián Palma    4 年前

    你可以试试 String#[] variableName[/regular expression/] ).

    names = "erik kalle johan anders erik kalle johan anders"
    # => "erik kalle johan anders erik kalle johan anders"
    names[/kalle/]
    # => "kalle"
    
        2
  •  81
  •   Christopher Oezbek    4 年前

    你可以用 [] :(这就像 match

    "foo+account2@gmail.com"[/\+([^@]+)/, 1] # matches capture group 1, i.e. what is inside ()
    # => "account2"
    "foo+account2@gmail.com"[/\+([^@]+)/]    # matches capture group 0, i.e. the whole match
    # => "+account2"
    
        3
  •  24
  •   Slartibartfast    16 年前

    如果只有一个匹配的存在是重要的,你可以去

    /regexp/ =~ "string"
    

    match 应该只返回第一次命中,而 scan

    matchData = "string string".match(/string/)
    matchData[0]    # => "string"
    matchData[1]    # => nil - it's the first capture group not a second match
    
        4
  •  11
  •   Felix yogesh kumar Panchal    9 年前

    /\$(?<dollars>\d+)\.(?<cents>\d+)/ =~ "$3.67" #=> 0
    dollars #=> "3"
    

    http://ruby-doc.org/core-2.1.1/Regexp.html

        5
  •  3
  •   Community CDub    8 年前

    正则表达式(regex)只是一个有限状态机(FSM)。

    它会一直尝试进行模式匹配,直到找到匹配(成功),或者直到所有路径都已探索但未找到匹配(失败)。

    在成功时,“这种状态是否可能?”的问题被回答为“是”。因此不需要进一步匹配,正则表达式返回。

    看见 this this 更多关于这方面的信息。

    进一步: here is an interesting example