正则表达式用HTML标签替换字符 [英] Regex Replacing Characters with HTML Tags
问题描述
我有这个示例字符串,我想在其中使用JavaScript中的正则表达式用一个打开和关闭强标签替换星号:
I have this sample string where I would like to replace the star with an opening and closing strong tag using regular expressions in JavaScript:
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 **),则不要将其替换为强标签.
The only caveat being that if there are two starts in a row (like 8**), that they not be replaced with the strong tags.
在此先感谢您的帮助.
推荐答案
也许您可以尝试这样的事情?
Maybe you could try something like this?
\*(\S[^\*]+\S)\*
+
表示1或更大,因此仅在 *
之间存在某些内容时才匹配.
The +
means 1 or more, so will only match if there is something between the *
.
[^ \ *]
表示不是星星的任何内容 *
.
The [^\*]
means anything that's not a star *
.
更新我已经更新了上面的正则表达式,以指定它与 *
和每个匹配项的第一个和最后一个字符之间的非空白字符不匹配.这样可以防止以下突出显示的位不正确匹配:
UPDATE
I've updated the regex above to specify that it doesn't match nonwhite space character's in between the *
and and the first and last characters of each match. This prevent's the highlighted bit below from incorrectly matching:
8 * *前缀.877和866将导致比800和888前缀更多的匹配项.*
注意*
这里是带注释的正则表达式(在javascript中)
Here is the same regex with comments (in 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的示例:
Finally, here is an example of the javascript you could use:
yourStringData.replace(/\*(\S[^\*]+\S)\*/g, "<strong>$1</strong>");
只需用包含要对其执行替换操作的数据的变量替换 yourStringData
.
Just replace the yourStringData
with a variable containing the data you want to run the replace against.
这篇关于正则表达式用HTML标签替换字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!