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)?
You could do like this:
"123 pre 456 post".sub(/(?<=pre)\s+\S+\s+(?=post)/, ' 789 ')
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With