Ruby regex- does gsub store what it matches?

醉酒当歌 提交于 2019-11-30 08:18:37

From the fine manual:

If replacement is a String it will be substituted for the matched text. It may contain back-references to the pattern’s capture groups of the form \d, where d is a group number, or \k<n>, where n is a group name. If it is a double-quoted string, both back-references must be preceded by an additional backslash. However, within replacement the special match variables, such as &$, will not refer to the current match.
[...]
In the block form, the current match string is passed in as a parameter, and variables such as $1, $2, $`, $&, and $' will be set appropriately. The value returned by the block will be substituted for the match on each call.

If you don't care about capture groups (i.e. things like (expr) in the regex) then you can use the block form and $&:

>> 'where is pancakes house?'.gsub(/is/) { "-#{$&}-" }
=> "where -is- pancakes house?"

If you do have capture groups then you can use \n in the replacement string:

>> 'where is pancakes house?'.gsub(/(is)/, '-\1-')
=> "where -is- pancakes house?"

or $n in the block:

>> 'where is pancakes house?'.gsub(/(is)/) { "-#{$1}-" }
=> "where -is- pancakes house?"

I found out here that gsub's matches could actually be accessed through the Regexp.last_match variable (class MatchData) like this:

my_string.gsub(my_regexp){ Regexp.last_match.inspect }

To give a more practical example, if you want to log all matches, it may be used as follows:

"Hello world".gsub(/(\w+)/) { Regexp.last_match.captures.each{ |match| Rails.logger.info "FOUND: #{match}"} }

#Rails log:
FOUND: Hello
FOUND: world

In your specific case, you could do something like this:

mystring.gsub(/(matchthisregex)/){ mystring = "replace_with_#{Regexp.last_match[0].to_s}this"}

For all ruby versions: Simple way to get matched string.

.gsub(/matched_sym/) {|sym| "-#{sym}-"}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!