How to Match all occurrences of a regex ?

How to Match all occurrences of a regex ?

Asked on December 15, 2018 in Regex.
Add Comment


  • 2 Answer(s)

    This will be the simple solution to the conversion:

    By using scan should do the work.It will Match all occurrences of a regex:

    string.scan(/regex/)
    

     

    Answered on December 15, 2018.
    Add Comment

    Just try this:

    To find all the matching strings, Use  scan method of string class.

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

    If you  want matchdata which is type of the object returned by, match method of  regular expression classes, use below 

    code:

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

     Benefit of having MatchData by using methods like 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]
    

    The special variables are   $&, $’, $1, $2.

    Answered on December 15, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.