Reputation: 6246
I have some input text, that could contain some patterns like
bla bla bla ###FOO WORLD### bla bla bla
bla bla bla ###FOO BOB###, ###FOO ALICE###bla bla bla
I want to process this and output
bla bla bla HELLO WORLD bla bla bla
bla bla bla HELLO BOB, HELLO ALICEbla bla bla
This is a bit more than find and replace because I want to preserve the content between the ### markers. I understand this should be easy with a regular expression... But I'm very rusty with regexes beyond anything but simple pattern matching.
What is the best way do do this? Do I need a regular expression object. Or does the string class have methods better suited to this?
Upvotes: 1
Views: 579
Reputation: 24350
s = "bla bla bla ###FOO BOB###, ###FOO ALICE###bla bla bla"
s.gsub(/###FOO (.*?)###/, 'HELLO \1')
# => bla bla bla HELLO BOB, HELLO ALICEbla bla bla
The FOO (.*?)
captures the text after FOO
, and the gsub
replaces the matching text with HELLO
followed by the capture text.
Upvotes: 4
Reputation: 9146
@Baldrick is Prefectly correct just another answer using blocks :)
a.gsub(/###FOO (.*?)###/) do
"HELLO " + $1
end
Upvotes: 0