1

I have a regexp that sets $1 : it corresponds to the text between ( and ) in : the_beginning(.*)the_end.

I want to replace the value corresponding to $1 with somethingelse, not all the regexp.

In real context :

my_string contains :

/* MyKey */ = { [code_missing]; MY_VALUE = "123456789"; [code_missing]; }

I want to replace "123456789" ( with "987654321" for example ). And this is my regexp :

"/\\* MyKey \\*/ = {[^}]*MY_VALUE = \"(.*)\";"

0

1 Answer 1

3

I'm still not sure exactly what you want, but here's some code that should help you:

str = "Hello this is the_beginning that comes before the_end of the string"
p str.sub /the_beginning(.+?)the_end/, 'new_beginning\1new_end'
#=> "Hello this is new_beginning that comes before new_end of the string"

p str.sub /(the_beginning).+?(the_end)/, '\1new middle\2'
#=> "Hello this is the_beginningnew middlethe_end of the string"

Edit:

theDoc = '/* MyKey */ = { [code_missing]; MY_VALUE = "123456789";'
regex  = %r{/\* MyKey \*/ = {[^}]*MY_VALUE = "(.*)";}
p theDoc[ regex, 1 ]   # extract the captured group
#=> "123456789"

newDoc = theDoc.sub( regex, 'var foo = \1' )
#=> "var foo = 123456789"  # replace, saving the captured information

Edit #2: Getting access to information before/after a match

regex = /\d+/
match = regex.match( theDoc )
p match.pre_match, match[0], match.post_match
#=> "/* MyKey */ = { [code_missing]; MY_VALUE = \""
#=> "123456789"
#=> "\";"

newDoc = "#{match.pre_match}HELLO#{match.post_match}"
#=> "/* MyKey */ = { [code_missing]; MY_VALUE = \"HELLO\";"

Note that this requires a regex that does not actually match the pre/post text.

If you need to specify the limits, and not the contents, you can use zero-width lookbehind/lookahead:

regex = /(?<=the_beginning).+?(?=the_end)/
m = regex.match(str)
"#{m.pre_match}--new middle--#{m.post_match}"
#=> "Hello this is the_beginning--new middle--the_end of the string"

…but now this is clearly more work than just capturing and using \1 and \2. I'm not sure I fully understand what you are looking for, why you think it would be easier.

Sign up to request clarification or add additional context in comments.

2 Comments

right, but is there a cleaner version that allows edition directly instead of copy the left and the right part?
I just want to replace "123456789", like you do with p str.sub /(the_beginning).+?(the_end)/, '\1new middle\2'. I was just thinking there is a better solution to do that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.