Monwe
Monwe

Reputation: 707

Maintaining a "variable" in regular expressions?

Is there any way using regular expressions to match and replace with a "variable string" like...

foo_1_a => bar_1_b
foo_2_a => bar_2_b
foo_3_a => bar_3_b

...

Using some expression with a variable "var" for example

"replace foo_var => [0-9]_a with bar_var_b "

Specifically I'm trying to take in one regex/replacement from command line using Ruby and executing all these replacements. Thanks.

Upvotes: 1

Views: 59

Answers (2)

humbroll
humbroll

Reputation: 347

Here we go.

result = "foo_1_a".match(/_([0..1])_/){ "bar_#{$1}_b" }
puts result # "bar_1_b" 

Upvotes: 0

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57640

If I understand you correctly, you are looking for back reference replace string. This is usually done by \1 or $1. The number 1 is the previously matched group's order.

So match foo_2_a by foo_(\d+)_a. Here parenthesis creates a group. And its the first group. So replace it with bar_\1_b. \1 will contain 2

More about Back Reference.

Upvotes: 1

Related Questions