Andrew
Andrew

Reputation: 239197

Ruby regex for parsing underscores as italic

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

Answers (1)

Ry-
Ry-

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

Related Questions