[ruby-core:105824] [Ruby master Bug#18271] Regexp inconsistency (repeatable)
From:
"zverok (Victor Shepelev)" <noreply@...>
Date:
2021-10-27 12:52:00 UTC
List:
ruby-core #105824
Issue #18271 has been updated by zverok (Victor Shepelev).
`$1` is global variable, `"#{$1}"` is evaluated BEFORE the method call, making a string "whatever was in `$1` at that moment":
```ruby
st = 'A. C. Cobble'
'foobar' =~ /f(.{2})/ # unrelated regex call, sets $1 to "oo"
st.gsub(/. ([A-Z])(?=.)/, ".#{$1}") # it is now an equivalent to calling with second arg = ".oo"
# => "A.oo.ooobble"
```
If I am understanding correctly what you want to achieve, you need to use `\1` (meaning "first group of currently evaluating regexp"):
```ruby
st.gsub(/. ([A-Z])(?=.)/, '.\1')
# => "A.C.Cobble"
```
----------------------------------------
Bug #18271: Regexp inconsistency (repeatable)
https://bugs.ruby-lang.org/issues/18271#change-94348
* Author: hanHoll (Han Holl)
* Status: Open
* Priority: Normal
* ruby -v: ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-linux]
* Backport: 2.6: UNKNOWN, 2.7: UNKNOWN, 3.0: UNKNOWN
----------------------------------------
han:~/au> irb >> st = 'A. C. Cobble'
=> "A. C. Cobble"
>> st.gsub(/\. ([A-Z])(?=\.)/, ".#{$1}")
=> "A.. Cobble"
>> st.gsub(/\. ([A-Z])(?=\.)/, ".#{$1}")
=> "A.C. Cobble"
>> RUBY_VERSION
=> "3.0.2"
>>
--
https://bugs.ruby-lang.org/
Unsubscribe: <mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>