正则表达式用 html 粗体标记替换星号字符 [英] Regex to replace asterisk characters with html bold tag

查看:79
本文介绍了正则表达式用 html 粗体标记替换星号字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人有好的正则表达式来做到这一点?例如:

Does anyone have a good regex to do this? For example:

This is *an* example

应该变成

This is <b>an</b> example

我需要在 Objective C 中运行它,但我可能可以自己解决这个问题.正则表达式给我带来了麻烦(如此生疏......).这是我到目前为止所拥有的:

I need to run this in Objective C, but I can probably work that bit out on my own. It's the regex that's giving me trouble (so rusty...). Here's what I have so far:

s/\*([0-9a-zA-Z ])\*/<b>$1<\/b>/g

但它似乎不起作用.有任何想法吗?谢谢:)

But it doesn't seem to be working. Any ideas? Thanks :)

感谢您的回答 :) 如果有人想知道在 Objective-C 中使用 RegexKitLite 会是什么样子:

Thanks for the answer :) If anyone is wondering what this looks like in Objective-C, using RegexKitLite:

NSString *textWithBoldTags = [inputText stringByReplacingOccurrencesOfRegex:@"\\*([0-9a-zA-Z ]+?)\\*" withString:@"<b>$1<\\/b>"];

再次实际上,为了包含更多用于加粗的字符,我将其更改为:

EDIT AGAIN: Actually, to encompass more characters for bolding I changed it to this:

NSString *textWithBoldTags = [inputText stringByReplacingOccurrencesOfRegex:@"\\*([^\\*]+?)\\*" withString:@"<b>$1<\\/b>"];

推荐答案

您只匹配 * 之间的一个字符.试试这个:

You're only matching one character between the *s. Try this:

s/\*([0-9a-zA-Z ]*?)\*/<b>$1<\/b>/g

或确保 * 之间至少有一个字符:

or to ensure there's at least one character between the *s:

s/\*([0-9a-zA-Z ]+?)\*/<b>$1<\/b>/g

这篇关于正则表达式用 html 粗体标记替换星号字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆