简体   繁体   English

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

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

I need to create a regex which should look for the last '*' irrespective of the whitespace in the string.我需要创建一个正则表达式,它应该查找最后一个 '*' 而与字符串中的空格无关。 Then, I need to replace that string with some text.然后,我需要用一些文本替换该字符串。

Currently, it is replacing the first occurence of '*' in the string.目前,它正在替换字符串中第一次出现的“*”。

How do I fix it?我如何解决它?

Here's my code:这是我的代码:

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

Here, the output should be 'Field Name* mandatory'.在这里,output 应该是“必填字段名称”。 But what I get is 'Field Name mandatory *'.但我得到的是“必填字段名称*”。

Instead of RegEx, use String#substring and String.lastIndexOf as below代替 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);

Still want to use RegEx? 还想使用正则表达式吗?

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

Short regex magic (shown on extended input str ):正则表达式魔术(显示在扩展输入str上):

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

  • (?=[^*]*$) - lookahead positive assertion, ensures that the former \* is matched only if it's followed by [^*]* (non-asterisk char right up to the end of the string $ ) (?=[^*]*$) - 前瞻肯定断言,确保前一个\*仅在其后跟[^*]*时匹配(直到字符串结尾的非星号字符$

Just let .* consume before last * and capture it..*在 last *之前消耗捕获它。 Replace with captured $1 mandatory .替换为mandatory捕获的$1

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

See this demo at regex101在 regex101 看到这个演示

  • If you have Field Name* *abc and want to strip out end as well, use (.*)\*.*如果您有Field Name* *abc并且还想去掉 end,请使用(.*)\*.*
  • If you have multline input, use [\S\s]* instead of .* to skip over newlines如果您有多行输入,请使用[\S\s]*而不是.*跳过换行符

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

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