[英]Regex Replacing Characters with HTML Tags
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: 我有以下示例字符串,我想在其中使用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)
The ideal output would be: 理想的输出为:
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)
The only caveat being that if there are two starts in a row (like 8**), that they not be replaced with the strong tags. 唯一的警告是,如果连续有两个开始(例如8 **),则不要将其替换为强标签。
Thank you in advance for any assistance. 预先感谢您的协助。
Maybe you could try something like this? 也许您可以尝试这样的事情?
\*(\S[^\*]+\S)\*
The +
means 1 or more, so will only match if there is something between the *
. +
表示1或更大,因此仅在*
之间存在匹配项时才匹配。
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* * prefix. 877 and 866 will result in more matches than 800 and 888 prefixes. *
8 *
* prefix. 877 and 866 will result in more matches than 800 and 888 prefixes. *
* prefix. 877 and 866 will result in more matches than 800 and 888 prefixes. *
* prefix. 877 and 866 will result in more matches than 800 and 888 prefixes. *
Note* * prefix. 877 and 866 will result in more matches than 800 and 888 prefixes. *
注意*
Here is the same regex with comments (in javascript) 这是带有注释的正则表达式(在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
Finally, here is an example of the javascript you could use: 最后,这是您可以使用的javascript的示例:
yourStringData.replace(/\*(\S[^\*]+\S)\*/g, "<strong>$1</strong>");
Just replace the yourStringData
with a variable containing the data you want to run the replace against. 只需使用包含要对之运行替换数据的变量替换
yourStringData
。
如果*
之间总是有单词 :
your_string.replace(/\*(\w+)\*/g, "<strong>$1</strong>");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.