问题
Answer from How do I get the match data for all occurrences of a Ruby regular expression in a string?:
input = "abc12def34ghijklmno567pqrs"
numbers = /\d+/
input.gsub(numbers) { |m| p $~ }
Result is as requested:
⇒ #<MatchData "12">
⇒ #<MatchData "34">
⇒ #<MatchData "567">
Would someone break down what the answerer is doing in input.gsub(numbers) { |m| p $~ }
?
Also, how would I access each of the MatchData
s?
回答1:
Since I’m the answerer, I would try to explain.
$~
is one of Ruby predefined globals. It returns the MatchData from the previous successful pattern match. It may be accessed using Regexp.last_match
as well.
As stated in the documentation, gsub
with block is commonly used to modify string, but here we use the fact it calls the codeblock on every match. Block variable m
there is a simple string for that match, so whether we need the whole MatchData
instance, we should use the predefined global $~
. In the mentioned example we simple print each MatchData
with p $~
.
The trick here is that $~
returns the last MatchData
. So, everything you need is to use $~
variable despite it’s repulsive look. Or, you might set:
my_beauty_name_match_data_var = $~
and play with the latter. Hope it helps.
来源:https://stackoverflow.com/questions/27632395/input-gsubnumbers-m-p-matching-data-in-ruby-for-all-occurrences-in-a