Ruby regex - gsub only captured group
You can't. gsub
replaces the entire match; it does not do anything with the captured groups. It will not make any difference whether the groups are captured or not.
In order to achieve the result, you need to use lookbehind and lookahead.
"5,214".gsub(/(?<=\d),(?=\d)/, '.')
Ruby regex capture groups in gsub
Remember that arguments to methods are evaluated immediately and the result of that is passed in to the method. If you want to make the substitution adapt to the match:
message.gsub!(/([[:alpha:]])/) { |m| z[a.index($1)] }
That employs a block that gets evaluated for each match.
ruby regex scan and gsub work differently with capture groups in blocks
No they don't behave the same.
The block form of gsub only accepts one parameter, so the second is going to be nil, hence your error.
See http://ruby-doc.org/core-2.1.4/String.html#method-i-gsub
Example of use: "hello".gsub(/./) {|s| s.ord.to_s + ' '}
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.The result inherits any tainting in the original string or any
supplied replacement string.
Ruby replace string with captured regex pattern
Try '\1'
for the replacement (single quotes are important, otherwise you need to escape the \
):
"foo".gsub(/(o+)/, '\1\1\1')
#=> "foooooo"
But since you only seem to be interested in the capture group, note that you can index a string with a regex:
"foo"[/oo/]
#=> "oo"
"Z_123: foobar"[/^Z_.*(?=:)/]
#=> "Z_123"
How to replace the captured group in Ruby
sub!
will replace the first match every iteration on part_number
which is outside of the loop.
What happens is:
In the first iteration, the first A will be replaced with A giving the same
R1L16SB#AA
^
In the second iteration, the first A will be replaced by B giving
R1L16SB#BA
^
In the third iteration, the first B will be replaced by C giving
R1L16SC#BA
^
One way to get the desired output is to put part_number = 'R1L16SB#AA'
inside the loop.
Ruby demo
Ruby Regex Group Replacement
You can use the following regex with back-reference \\1
in the replacement:
reg = /(\\e\[(?:[0-9]{1,2}|[3,9][0-8])m)+Text/
mystring = "\\e[1mHello there\\e[34m\\e[40mText\\e[0m\\e[0m\\e[22m"
puts mystring.gsub(reg, '\\1New Text')
mystring = "\\e[1mHello there\\e[44m\\e[34m\\e[40mText\\e[0m\\e[0m\\e[22m"
puts mystring.gsub(reg, '\\1New Text')
Output of the IDEONE demo:
\e[1mHello there\e[40mNew Text\e[0m\e[0m\e[22m
\e[1mHello there\e[40mNew Text\e[0m\e[0m\e[22m
Mind that your input has backslash \
that needs escaping in a regular string literal. To match it inside the regex, we use double slash, as we are looking for a literal backslash.
Using named capture groups inside Ruby gsub blocks (regex)
You are looking for
"foo /(bar)".gsub(/(?<my_word> \(.*?\) )/x) do |match|
puts "$1 = #{$1} and $my_word = #{$~[:my_word]}"
end
Ruby - best way to extract regex capture groups?
Since v2.4.6, Ruby has had named_captures
, which can be used like this. Just add the ?<some_name>
syntax inside a capture group.
/(\w)(\w)/.match("ab").captures # => ["a", "b"]
/(\w)(\w)/.match("ab").named_captures # => {}
/(?<some_name>\w)(\w)/.match("ab").captures # => ["a"]
/(?<some_name>\w)(\w)/.match("ab").named_captures # => {"some_name"=>"a"}
Even more relevant, you can reference a named capture by name!
result = /(?<some_name>\w)(\w)/.match("ab")
result["some_name"] # => "a"
Ruby Regexp gsub, replace instances of second matching character
You need to capture \w
to be able to refer to the submatch.
Use
"this-is-a-string".gsub(/-(\w)/) {$~[1].upcase}
# => thisIsAString
See the Ruby demo
Note that $~[1]
inside the {$~[1].upcase}
block is actually the text captured with (\w)
, the $~
is a matchdata object instantiated with gsub
and [1]
is the index of the first group defined with a pair of unescaped parentheses.
See more details about capturing groups in the Use Parentheses for Grouping and Capturing section at regular-expressions.info.
Related Topics
Accepts_Nested_Attributes_For Rails 4 Is Not Deleting
Verb-Agnostic Matching in Sinatra
How to Run Ruby 2.0 with Jruby 1.7
What Is a Worker in Ruby/Rails
I'm Getting "Found Character That Cannot Start Any Token While Scanning for the Next Token"
Ruby - Activerecord::Connectionnotestablished
Heroku: How to Push Seeds.Rb to Existing Rails App
Spork 0.9.2 and Rspec 3.0.0 = Uninitialized Constant Rspec::Core::Commandline (Nameerror)
Vi Input Mode in Command Line Matlab
Customize Error Message with Simple_Form
Rails: Find Rows Without Connection in Habtm Relation
Deploy with Capistrano Failing
How to Instruct Capistrano 3 to Load My Shell Environment Variables Set at Remote Host
Escape Double and Single Backslashes in a String in Ruby
Ruby String.Encode Still Gives "Invalid Byte Sequence in Utf-8"
Error Occurred While Installing Mini_Racer (0.2.0)
Are Ruby 1.9 Regular Expressions Equally Powerful to a Context Free Grammar