1

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?

2 Answers 2

4
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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.