Reputation: 239197
I'm trying to add italics to text that matches a regular expression, but it's failing:
string = 'this should have _emphasis_ but this_one_should_not'
string.gsub!(%r{ (\*|_) (\S|\S.*?\S) \1 }x, %{<em>\\2</em>})
string.should == 'this should have <em>emphasis</em> but this_one_should_not'
# actual = 'this should have <em>emphasis</em> but this<em>one</em>should_not'
The one with italics in the middle is incorrectly being turned italic. I copied this code from somewhere else, but I need to adjust it so that it works for this use case.
Upvotes: 1
Views: 439
Reputation: 225281
Here's one that works:
string = 'this should have _emphasis_ but this_one_should_not'
string.gsub!(%r{(^|\s)([*_])(.+?)\2(\s|$)}x, %{\\1<em>\\3</em>\\4})
string.should == 'this should have <em>emphasis</em> but this_one_should_not'
And here's a demo.
Upvotes: 2