Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Elegant way to substitute captured part of string

Tags:

regex

ruby

I want to do a string substitution where if I find a string between two terms I replace it, so when I have a string like:

"123 pre 456 post"

I can get:

"123 pre 789 post"

I can do this by doing something like:

string.sub(/(pre\s+)\S+(\s+post)/, "\\1789\\2")

However, I'd like to avoid using the two captures if possible. In fact, I'd like to use a regular expression like this instead: /pre\s+(\S+)\s+post/ and get the range of the capture and then replace it. Is there a way to do that (using the standard Ruby libraries)?

like image 944
ThomasW Avatar asked Feb 19 '23 03:02

ThomasW


2 Answers

You could do like this:

"123 pre 456 post".sub(/(?<=pre)\s+\S+\s+(?=post)/, ' 789 ')
like image 95
xdazz Avatar answered Feb 20 '23 15:02

xdazz


The []= operator does this, although it modifies the string in place

s = "123 pre 456 post"
s[/pre\s+(\S+)\s+post/] = '789'

replaces the entire rexep match, and

s = "123 pre 456 post"
s[/pre\s+(\S+)\s+post/, 1] = '789'

replaces the specified capture groups (you can do this with named capture groups too).

Should work on 1.8.7 (although no named capture groups there I think) and 1.9

like image 34
Frederick Cheung Avatar answered Feb 20 '23 16:02

Frederick Cheung