Jak dopasować wszystkie wystąpienia wyrażenia regularnego

Czy istnieje szybki sposób na znalezienie każdego dopasowania wyrażenia regularnego w Rubim? Przejrzałem obiekt Regex w Ruby STL i szukałem w Google bez skutku.

 605
Author: the Tin Man, 2008-09-17

4 answers

Za pomocą scan powinno wystarczyć:

string.scan(/regex/)
 845
Author: Jean,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-18 06:23:21

Aby znaleźć wszystkie pasujące łańcuchy, użyj łańcuchów scan metoda.

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

Jeśli chcesz, MatchData, który jest typem obiektu zwracanego metodą Regexp match, Użyj:

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

Zaletą używania MatchData jest to, że możesz używać metod takich jak 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]

Zobacz te pytania, jeśli chcesz wiedzieć więcej:

Czytanie o zmiennych specjalnych$&, $', $1, $2 W Ruby też będzie pomocny.

 77
Author: sudo bangbang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-04-09 16:40:26

Jeśli masz Wyrażenie regularne z grupami:

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

Możesz użyć metody String scan, aby znaleźć pasujące grupy:

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

Aby znaleźć pasujący wzór:

str.to_enum(:scan,re).map {$&}
#> ["54m", "1t", "3r"]
 12
Author: MVP,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-04-09 16:41:42

Możesz użyć string.scan(your_regex).flatten. Jeśli wyrażenie regularne zawiera grupy, zwróci je w jednej tablicy.

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

Regex może być również nazwą grupy.

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

Możesz również użyć gsub, to tylko jeszcze jeden sposób, jeśli chcesz MatchData.

str.gsub(/\d/).map{ Regexp.last_match }
 1
Author: Datt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-04-09 17:07:33