【问题标题】:Create a regex to replace the last occurrence of a character in a string创建一个正则表达式来替换字符串中最后一次出现的字符
【发布时间】:2020-03-18 03:52:45
【问题描述】:

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

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

我该如何解决?

这是我的代码:

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

此处,输出应为“必填字段名称”。但我得到的是“必填字段名称 *”。

【问题讨论】:

    标签: javascript regex string replace


    【解决方案1】:

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

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

    【讨论】:

    • 你的解决方案是正确的,但我这里需要使用正则表达式。
    • @Sunny 添加了正则表达式。
    • @Sunny BTW,你为什么只需要 RegEx 解决方案?
    • 我们在项目中的任何地方都使用正则表达式进行任何替换。因此,这里也需要使用它。
    • @Sunny 我建议尽可能使用字符串替换,它会比正则表达式替换更快。
    【解决方案2】:

    regex 魔法(显示在扩展输入 str):

    const regex = /\*(?=[^*]*$)/m,
          str = 'Field Name* * * * ',
          replaceStr = ' mandatory',
          result = str.replace(regex, replaceStr);
    console.log('Substitution result: ', result);
    • (?=[^*]*$) - 前瞻肯定断言,确保仅当前一个 \* 后跟 [^*]* 时才匹配(直到字符串 $ 末尾的非星号字符)

    【讨论】:

      【解决方案3】:

      .*consume在最后一个*capture之前。替换为captured $1mandatory

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

      See this demo at regex101

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

      【讨论】:

        猜你喜欢
        • 2011-09-10
        • 2021-04-29
        • 2011-04-19
        • 2011-07-26
        • 1970-01-01
        • 2012-11-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多