简体   繁体   English

正则表达式替换但忽略最后一个字符

[英]Regex replace but ignore last character

I am trying to replace我正在尝试替换

/ok/how/are

with

$ok, $how, $are

using regex使用正则表达式

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

and result is结果是

$ok, $how, $are, 

I can't use another statement to remove last leading , how can I get desire result without last ,我不能使用另一个语句来删除最后一个前导,没有最后一个我怎么能得到期望的结果,

You can use two captured group, one with end of string anchor another without anchor and replace value accordingly您可以使用两个捕获的组,一个带有字符串锚的结尾,另一个没有锚并相应地替换值

 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)

If the only function you can use in replace , you can use your pattern and replace the trailing comma with an empty space.如果您可以在replace中使用唯一的 function ,则可以使用您的模式并将尾随逗号替换为空格。

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

Another option without a regex could be using a combination of split on a forward slash, map to prepend a dollar sign and join on a comma and space.没有正则表达式的另一个选项可能是在正斜杠上使用拆分组合, map在前面加上美元符号并加入逗号和空格。

To remove the empty entry after split you could use for example .filter(Boolean)要在拆分后删除空条目,您可以使用例如.filter(Boolean)

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

Several solutions are possible: if it's about replacing / with $ and separating the resulting terms with a comma this may be viable.有几种解决方案是可能的:如果是用$替换/并用逗号分隔结果项,这可能是可行的。

A second solution is using named capture groups ( see here and snippet) in your regular expression第二种解决方案是在您的正则表达式中使用命名的捕获组参见此处和片段)

 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}`; }) );

Here is another variant of lambda/anonymous function based approach in .replace .这是.replace中基于 lambda/匿名 function 方法的另一种变体。 This regex uses a capture group inside a lookahead that asserts whether we have / ahead of us or it is end of string.这个正则表达式在前瞻中使用了一个捕获组,它断言我们前面是否有/或者它是字符串的结尾。

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

Details:细节:

  • \/([az\d]+) : Match / followed by 1+ letter (ignore case) or digit \/([az\d]+) :匹配/后跟 1+ 个字母(忽略大小写)或数字
  • (?=(\/|$)) : Lookahead that asserts presence of / or end of string and captures it in 2nd capture group (?=(\/|$)) :断言存在/或字符串结尾并在第二个捕获组中捕获它的前瞻

  • ($0, $1, $2) : Here $0 will be full matched string and $1, $2 are first and second capture group ($0, $1, $2) :这里$0将是完全匹配的字符串, $1, $2是第一个和第二个捕获组

  • '$' + $1 : Concatenates $ and 1st capture group '$' + $1 : 连接$和第一个捕获组
  • ($2? ", ": "") : Use ternary operator it makes a decision whether capture group #2 or $2 is empty or not. ($2? ", ": "") :使用三元运算符决定捕获组#2 或$2是否为空。 If it is not empty then it adds ", " in final output otherwise an empty string is added.如果不为空,则在最后的 output 中添加", " ,否则添加空字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM