2012-01-25 22 views
1

我想斜体添加到正则表达式匹配的文本,但它的失败:红宝石的正则表达式解析强调斜体

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' 

中间用斜体一个错误被打开斜体。我从其他地方复制了这段代码,但我需要调整它以使其适用于此用例。

+0

你正在处理包含Markdown格式的文本吗?如果是这样,为什么不使用宝石来转换它?它会自动添加格式。 –

+0

,因为我只需要支持一小组markdown(em,strong,links等),我找不到任何可以选择我想要转换的元素的选项。 – Andrew

回答

2

这里有一个工程:

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' 

而且here's a demo

+0

@Andrew:适用于我:http://codepad.org/ijzZYMb1 – Ryan

+0

...但是,它也包裹着强大的标签:'** bold **'变成了'* strong *' – Andrew

+0

@Andrew:同样地事先做:http://codepad.org/urkFi2M7 – Ryan