user1049097
user1049097

Reputation: 1901

How to modify a string if the first two letters match a pattern?

I have strings like this:

$5.00 off blah blah
5% off blah blah
This off should not match

I'd like to match strings that start like ^([$]?[\d.]+[%]?) off .*

And converts them to this:

<strong>$5.00 off</strong> blah blah
<strong>5% off</strong> blah blah
This off should not match

Here is what I have right now and stuck (new to Ruby):

def highlight_name(name)
  words = name.dup.split

end

Upvotes: 0

Views: 55

Answers (2)

Thilo
Thilo

Reputation: 17735

Based on apneadiving's answer, modified to do what you want:

string.gsub(/^([$]?[\d.]+[%]? off)( .*)$/, '<strong>\1</strong>\2' )

Upvotes: 0

apneadiving
apneadiving

Reputation: 115541

This should do the trick:

string.gsub(/^([$]?[\d.]+[%]?) off .*/, "<strong> \\0 </strong>" )

\\O refers to the matched string.

Upvotes: 1

Related Questions