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

匹配正则表达式的所有匹配项

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

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

    3 回复  |  直到 6 年前
        1
  •  862
  •   Andrew Marshall    14 年前

    使用 scan 应该做到这一点:

    string.scan(/regex/)
    
        2
  •  80
  •   the Tin Man    6 年前

    要查找所有匹配的字符串,请使用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也会有所帮助。

        3
  •  12
  •   the Tin Man    6 年前

    如果你有一个带有组的正则表达式:

    str="A 54mpl3 string w1th 7 numbers scatter3r ar0und"
    re=/(\d+)[m-t]/
    

    你可以使用String scan 查找匹配组的方法:

    str.scan re
    #> [["54"], ["1"], ["3"]]
    

    要查找匹配的模式,请执行以下操作:

    str.to_enum(:scan,re).map {$&}
    #> ["54m", "1t", "3r"]
    

    或者有完整匹配数据的解决方案:

    str.to_enum(:scan,re).map{Regexp.last_match}
    #> [#<MatchData "54m" 1:"54">, #<MatchData "1t" 1:"1">, #<MatchData "3r" 1:"3">]
    
    str.to_enum(:scan,re).map {$~}
    #> [#<MatchData "54m" 1:"54">, #<MatchData "1t" 1:"1">, #<MatchData "3r" 1:"3">]
    
        4
  •  2
  •   the Tin Man    6 年前

    您可以使用 string.scan(your_regex).flatten 。如果正则表达式包含组,它将返回一个纯数组。

    string = "A 54mpl3 string w1th 7 numbers scatter3r ar0und"
    your_regex = /(\d+)[m-t]/
    string.scan(your_regex).flatten
    => ["54", "1", "3"]
    

    正则表达式也可以是一个命名组。

    string = 'group_photo.jpg'
    regex = /\A(?<name>.*)\.(?<ext>.*)\z/
    string.scan(regex).flatten
    

    您还可以使用 gsub ,如果你想要MatchData,这只是另一种方式。

    str.gsub(/\d/).map{ Regexp.last_match }
    
    推荐文章