Project

General

Profile

Actions

Bug #18271

closed

Regexp inconsistency (repeatable)

Added by hanHoll (Han Holl) about 1 month ago. Updated about 1 month ago.

Status:
Closed
Priority:
Normal
Assignee:
-
Target version:
-
ruby -v:
ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-linux]
[ruby-core:105822]

Description

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"

Updated by zverok (Victor Shepelev) about 1 month ago

$1 is global variable, "#{$1}" is evaluated BEFORE the method call, making a string "whatever was in $1 at that moment":

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"):

st.gsub(/. ([A-Z])(?=.)/, '.\1')
# => "A.C.Cobble"
Actions #2

Updated by jeremyevans0 (Jeremy Evans) about 1 month ago

  • Status changed from Open to Closed
Actions

Also available in: Atom PDF