簡體   English   中英

正則表達式用HTML標簽替換字符

[英]Regex Replacing Characters with HTML Tags

我有以下示例字符串,我想在其中使用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 **),則不要將其替換為強標簽。

預先感謝您的協助。

也許您可以嘗試這樣的事情?

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

+表示1或更大,因此僅在*之間存在匹配項時才匹配。

[^\\*]表示不是星號*任何內容。

更新我已經更新了上面的正則表達式,以指定它與*以及每個匹配項的第一個和最后一個字符之間的非空白字符不匹配。 這可以防止以下突出顯示的位不正確匹配:

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. *注意*

這是帶有注釋的正則表達式(在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

如果*之間總是有單詞

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM