[英]Regex Replacement
我有一個字符串:
users/554983490\\/Another+Test+/Question????\\/+dhjkfsdf/
我將如何編寫一個與所有不帶反斜杠的正斜杠匹配的RegExp?
編輯:有沒有一種方法可以不使用否定的lookbehinds?
您可以使用:
/(?<!\\)\//
這稱為否定性回溯 。
我用/作為分隔符
(?<! <-- Start of the negative lookbehind (means that it should be preceded by the following pattern)
\\ <-- The \ character (escaped)
) <-- End of the negative lookbehind
\/ <-- The / character (escaped)
如果您的正則表達式支持負向后看 :
/(?<!\\)\//
否則,您還需要匹配/
之前的字符 :
/(^|[^\\])\//
這匹配字符串( ^
)的開頭,或( |
)除\\
( [^\\\\]
)以外的任何其他字符作為捕獲組#1 ()
。 然后,它匹配文字/
后。 /
之前的任何字符都將存儲在捕獲組$1
因此如果要進行替換,則可以將其放回原位。
示例(JavaScript):
'st/ri\\/ng'.replace(/(^|[^\\])\//, "$1\\/");
// returns "st\/ri\/ng"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.