代码之家  ›  专栏  ›  技术社区  ›  Chris Bunch

如何在Ruby中匹配正则表达式的所有出现

  •  651
  • Chris Bunch  · 技术社区  · 18 年前

    在Ruby中,有没有一种快速的方法可以找到正则表达式的每个匹配项?我查看了Ruby STL中的Regex对象,并在谷歌上进行了搜索,但一无所获。

    6 回复  |  直到 3 年前
        1
  •  1
  •   Victor Cordeiro Costa    4 年前

    使用 scan 应该做到这一点:

    string.scan(/regex/)
    
        2
  •  1
  •   some_guy    4 年前

    要查找所有匹配的字符串,请使用String scan 方法。

    str = "A 54mpl3 string w1th 7 numb3rs scatter36 ar0und"
    str.scan(/\d+/)
    #=> ["54", "3", "1", "7", "3", "36", "0"]
    

    如果你愿意, MatchData ,这是Regexp返回的对象的类型 match 方法,使用:

    str.to_enum(:scan, /\d+/).map { Regexp.last_match }
    #=> [#<MatchData "54">, #<MatchData "3">, #<MatchData "1">, #<MatchData "7">, #<MatchData "3">, #<MatchData "36">, #<MatchData "0">]
    

    使用的好处 匹配数据 你可以使用以下方法 offset :

    match_datas = str.to_enum(:scan, /\d+/).map { Regexp.last_match }
    match_datas[0].offset(0)
    #=> [2, 4]
    match_datas[1].offset(0)
    #=> [7, 8]
    

    如果您想了解更多信息,请查看这些问题:

    阅读特殊变量 $& , $' , $1 , $2 Ruby也会有所帮助。

    推荐文章