[英]How do I enforce that certain characters must be present when there is an optional character before them?
[英]Regex to find characters not having a certain character before them
我在Javascript中有這些字符串:
var string1 = '#23 the id of this report is \\# 23';
var string2 = '# \\# \\# # \\\\# #';
我想做一個.replace()
替換所有 #
無 \\\\
他們之前 \\\\#
但不能寫入正確的正則表達式。
string2
結果應為\\\\# \\\\# \\\\# \\\\# \\\\\\\\# \\\\#
有什么想法嗎?
工作解決方案:
嘗試使用此替換功能
.replace(/[\\]{0,1}#/g, "\\#")
DEMO
var string1 = '#23 the id of this report is \\\\# 23'; alert(string1.replace(/[\\\\]{0,1}#/g, "\\\\#")); var string2 = '# \\\\# \\\\\\# \\# \\\\\\\\# #'; alert(string2.replace(/[\\\\]{0,1}#/g, "\\\\#")); var string3 = '# \\\\# \\\\# # \\\\\\\\# #'; alert(string3.replace(/[\\\\]{0,1}#/g, "\\\\#"));
您可以先將沒有反斜杠的哈希標記作為目標,方法是先將它們與反斜杠匹配,然后作為替代(使用交替運算符,也稱為管道, |
)嘗試單獨使用哈希標記,因此將匹配哈希標記之前沒有反斜杠,並且在兩種情況下都用\\#
代替:
var string2 = '# \\\\# \\\\# # \\\\\\\\# #'; var maybe_escaped = /\\\\#|#/g; var result = string2.replace(maybe_escaped, '\\\\#'); document.getElementById('result').textContent = JSON.stringify(result);
<div id='result' style="font-family: monospace; "></div>
一種替代方法是僅使用以下正則表達式,盡管上面的正則表達式可以被認為更好地體現了問題的消極后顧之憂,並且更具通用性。
/\\?#/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.