首页 文章

匹配所有出现的正则表达式

提问于
浏览
537

有没有快速的方法来找到Ruby中正则表达式的每个匹配?我查看了Ruby STL中的Regex对象并在Google上搜索无济于事 .

3 回答

  • 48

    使用scan应该可以做到这一点:

    string.scan(/regex/)
    
  • 759

    要查找所有匹配的字符串,请使用 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">]
    

    拥有 MatchData 的好处是你可以使用像 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]
    

    如果您想了解更多,请参阅这些问题
    How do I get the match data for all occurrences of a Ruby regular expression in a string?
    Ruby regular expression matching enumerator with named capture support
    How to find out the starting point for each match in ruby

    在ruby中阅读特殊变量 $&$'$1$2 将会非常有帮助 .

  • 8

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

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

    您可以使用scan of string方法查找匹配的组:

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

    要找到匹配的模式:

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

相关问题