繁体   English   中英

创建一个正则表达式来替换字符串中最后一次出现的字符

[英]Create a regex to replace the last occurrence of a character in a string

我需要创建一个正则表达式,它应该查找最后一个 '*' 而与字符串中的空格无关。 然后,我需要用一些文本替换该字符串。

目前,它正在替换字符串中第一次出现的“*”。

我如何解决它?

这是我的代码:

const regex = /\*/m;
const str = 'Field Name* * ';
const replaceStr = ' mandatory';
const result = str.replace(regex, replaceStr);
console.log('Substitution result: ', result);

在这里,output 应该是“必填字段名称”。 但我得到的是“必填字段名称*”。

代替 RegEx,使用String#substringString.lastIndexOf如下

 const str = 'Field Name* * '; const replaceStr = 'mandatory'; const lastIndex = str.lastIndexOf('*'); const result = str.substring(0, lastIndex) + replaceStr + str.substring(lastIndex + 1); console.log('Substitution result: ', result);

还想使用正则表达式吗?

 const regex = /\*([^*]*)$/; const str = 'Field Name* * Hello World;'; const replaceStr = ' mandatory'. const result = str,replace(regex, (m; $1) => replaceStr + $1). console:log('Substitution result, '; result);

正则表达式魔术(显示在扩展输入str上):

 const regex = /\*(?=[^*]*$)/m, str = 'Field Name* * * * ', replaceStr = ' mandatory', result = str.replace(regex, replaceStr); console.log('Substitution result: ', result);

  • (?=[^*]*$) - 前瞻肯定断言,确保前一个\*仅在其后跟[^*]*时匹配(直到字符串结尾的非星号字符$

.*在 last *之前消耗捕获它。 替换为mandatory捕获的$1

 let str = 'Field Name* * '; let res = str.replace(/(.*)\*/,'$1mandatory'); console.log(res);

在 regex101 看到这个演示

  • 如果您有Field Name* *abc并且还想去掉 end,请使用(.*)\*.*
  • 如果您有多行输入,请使用[\S\s]*而不是.*跳过换行符

暂无
暂无

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

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