Chris
Chris

Reputation: 6246

Ruby find and replace around a simple pattern

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

Answers (2)

Baldrick
Baldrick

Reputation: 24350

s = "bla bla bla ###FO­O BOB##­#, ###FO­O ALICE­###bla bla bla"
s.gsub(/###F­OO (.*?)­###/, 'HELL­O \1')
# => bla bla bla HELLO BOB, HELLO ALICEbla bla bla

The F­OO (.*?) captures the text after FOO, and the gsub replaces the matching text with HELLO followed by the capture text.

Upvotes: 4

Pritesh Jain
Pritesh Jain

Reputation: 9146

@Baldrick is Prefectly correct just another answer using blocks :)

 a.gsub(/###FOO (.*?)###/) do
     "HELLO " + $1
 end

Upvotes: 0

Related Questions