我需要一個用于 Javascript 的正則運算式來替換一個字串(例如 >//<),如果它在任何型別的引號內。例如
>This is a test "With a text including // and more" for replacement<
我無法讓 Reg Expression 規則的組合起作用,我不擅長這個,對你們中的一些人來說很容易;)
uj5u.com熱心網友回復:
我支持@gog 的回答,兩個正則運算式替換是可行的方法。外部.replace查找參考的文本,嵌套.replace替換出現 1 次以上的//to \\:
const input = `This is a test "with quoted text including // and more // stuff",
"this has none",
this // is outside quotes,
and "this has one //".`
let result = input.replace(/"[^"]*"/g, m => {
return m.replace(/\/\//g, '\\\\')
});
console.log(result);
輸出:
This is a test "with quoted text including \\ and more \\ stuff",
"this has none",
this // is outside quotes,
and "this has one \\".
uj5u.com熱心網友回復:
使用兩個正則運算式會更容易。分別匹配參考和非參考的內容,并在回呼函式中進行實際替換:
s = 'This "is" a // test "With a text including // and more" for "replacement"'
r = s.replace(
/([^"] )|(". ?")/g,
(_, nonq, quot) =>
nonq || quot.replace('//', 'hey'))
console.log(r)
uj5u.com熱心網友回復:
重要的提示:
經過進一步研究,在使用帶有量詞的正則運算式“環視”斷言時要小心。雖然此解決方案適用于我的 Node.js 16.14.2 環境,但對正則運算式此功能的更廣泛支持似乎有限。
我的答案:
在這種情況下,您可以使用帶有量詞的先行斷言和后行斷言。以下正則運算式將滿足您對提供的測驗字串進行實際匹配的要求:
/(?<=").*(?=")/
當然,由于您使用的是 JavaScript,因此可以將此正則運算式與.replace()字串方法一起使用來替換正則運算式匹配的內容:
const testString =
'>This is a test "With a text including // and more" for replacement<';
testString.replace(/(?<=".*)\/\/(?=.*")/, 'duck');
// >This is a test "With a text including duck and more" for replacement<
希望這可以幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/535358.html
下一篇:通過另一個函式運行匯入的函式
