2012-03-28 55 views
2

我有这样的样本串,我想有一个开口,以取代明星和关闭使用JavaScript的正则表达式较强的触杀:正则表达式替换字符的HTML标签

To increase search results, use the 8** prefix. 
877 and 866 will result in more matches than 800 and 888 prefixes. 
*Note*: The pattern for a custom number can be more than 7 digits. For example: 1-800-Mat-tres(s) 

理想的输出将是:

To increase search results, use the 8** prefix. 
877 and 866 will result in more matches than 800 and 888 prefixes. 
<strong>Note</strong>: The pattern for a custom number can be more than 7 digits. For example: 1-800-Mat-tres(s) 

唯一需要注意的是,如果连续有两个开头(如8 **),那么它们不会被强标签取代。

非常感谢您的帮助。

+1

你有没有在自己所有尝试新鲜事物? – 2012-03-28 22:32:00

+1

@AdamZalcman好点。我需要更多地鼓励。 – Kyle 2012-03-28 22:40:28

+0

是的,我试过 var thisContent = thisContent.replace(/\*(.*?)\*/ g,'$&'); – SkyOut 2012-03-29 13:38:36

回答

3

也许你可以尝试这样的事情?

\*(\S[^\*]+\S)\* 

+指1或更多,所以如果存在*之间的事情将只匹配。

[^\*]意味着任何不是明星*

UPDATE 我已经更新了上述正则表达式来指定,它并没有非空白字符的在*和每场比赛的第一个和最后一个字符之间不匹配。该防止的不正确地匹配下面重点介绍一下:

8 * * prefix. 877 and 866 will result in more matches than 800 and 888 prefixes. *注*

这里是一样的正则表达式与评论(在JavaScript)

"\\*" +  // Match the character “*” literally 
"\\S" +  // Match a single character that is a “non-whitespace character” 
"[^\\*]" + // Match any character that is NOT a * character 
    "+" +  // Between one and unlimited times, as many times as possible, giving back as needed (greedy) 
"\\S" +  // Match a single character that is a “non-whitespace character” 
"\\*"   // Match the character “*” literally 

最后,这里是JavaScript的一个例子你可以使用:

yourStringData.replace(/\*(\S[^\*]+\S)\*/g, "<strong>$1</strong>"); 

只需更换yourStringData具有可变包含数据要运行取而代之。

+0

这个正则表达式非常好。我发现的唯一问题是,它并没有删除那里的原始明星。所以内容被合适地包裹在强标签中,但星星仍然在里面。 – SkyOut 2012-03-29 13:41:14

+0

更具体地说,这是我正在使用的替换: 'code'var thisContent = thisContent.replace(/ \ * \ S [^ \ *] + \ S \ */g,“$&”); '代码' – SkyOut 2012-03-29 13:58:26

+0

@SkyOut我认为你在替换中获得'*'的原因是它需要一个围绕'\ S'添加的组,如下所示:'\ *(\ S [^ \ * ] + \ S)\ *' - 我想....让我知道这是否有效。 – Robbie 2012-03-29 16:12:32

3

如果总是有*的之间:

your_string.replace(/\*(\w+)\*/g, "<strong>$1</strong>"); 
+0

请注意,如果还有其他问题,在''''''''''''''''''''''空间或任何类型的标点符号之间(我想这会是?)。它也会匹配'**'和'* text *'的开头之间的任何内容 - 这与它应该匹配的内容相反 – Robbie 2012-03-29 09:33:05