簡體   English   中英

正則表達式替換但忽略最后一個字符

[英]Regex replace but ignore last character

我正在嘗試替換

/ok/how/are

$ok, $how, $are

使用正則表達式

str.replace(/\/([0-9a-zA-Z]+)/g, '\$$1,')

結果是

$ok, $how, $are, 

我不能使用另一個語句來刪除最后一個前導,沒有最后一個我怎么能得到期望的結果,

您可以使用兩個捕獲的組,一個帶有字符串錨的結尾,另一個沒有錨並相應地替換值

 let str = `/ok/how/are` let final = str.replace(/\/([a-zA-Z\d]+)$|\/([a-zA-Z\d]+)/g, (_, g1, g2) => g1? `$${g1}`: `$${g2}, `) console.log(final)

如果您可以在replace中使用唯一的 function ,則可以使用您的模式並將尾隨逗號替換為空格。

 const regex = /\/([a-z0-9]+)/g; let str = `/ok/how/are`; str = str.replace(regex, "$$$1, ").replace(/, $/, ''); console.log(str);

沒有正則表達式的另一個選項可能是在正斜杠上使用拆分組合, map在前面加上美元符號並加入逗號和空格。

要在拆分后刪除空條目,您可以使用例如.filter(Boolean)

 let str = "/ok/how/are"; str = str.split("/").filter(Boolean).map(x => "$" + x).join(", "); console.log(str)

有幾種解決方案是可能的:如果是用$替換/並用逗號分隔結果項,這可能是可行的。

第二種解決方案是在您的正則表達式中使用命名的捕獲組參見此處和片段)

 console.log( `$${"/ok/how/are".split("\/").filter(v => /^[0-9a-zA-Z]+$/g.test(v)).join(", $")}` ); // use es2018 named capture groups in regex // ----------------------------------------- console.log( "/ok/how/are".replace(/\/((?<end>\w+$)|(?<within>\w+))/g, (...args) => { const { within, end } = args[args.length-1]; return within? `$${within}, `: `$${end}`; }) );

這是.replace中基於 lambda/匿名 function 方法的另一種變體。 這個正則表達式在前瞻中使用了一個捕獲組,它斷言我們前面是否有/或者它是字符串的結尾。

 let str = '/ok/how/are'; var repl = str.replace(/\/([az\d]+)(?=(\/|$))/ig, ($0, $1, $2) => '$' + $1 + ($2? ", ": "")); console.log(repl); //=> "$ok, $how, $are"

細節:

  • \/([az\d]+) :匹配/后跟 1+ 個字母(忽略大小寫)或數字
  • (?=(\/|$)) :斷言存在/或字符串結尾並在第二個捕獲組中捕獲它的前瞻

  • ($0, $1, $2) :這里$0將是完全匹配的字符串, $1, $2是第一個和第二個捕獲組

  • '$' + $1 : 連接$和第一個捕獲組
  • ($2? ", ": "") :使用三元運算符決定捕獲組#2 或$2是否為空。 如果不為空,則在最后的 output 中添加", " ,否則添加空字符串。

暫無
暫無

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

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