【问题标题】:RegEx to return only matching group using only replace method正则表达式仅使用替换方法返回匹配组
【发布时间】:2019-07-01 03:13:11
【问题描述】:

有没有办法只使用替换只返回匹配组?

我有这个字符串,

"xml版本2.1.2-翡翠https://www.example.com"

我想从中提取版本。

我正在使用这个正则表达式:

const regex = /\sversion\s(.*?)\s/;
const str = `xml version 2.1.2-emerald https://www.example.com`;
const subst = `$1`;
const result = str.replace(regex, subst);

console.log('Substitution result: ', result); 
// desired result: "2.1.2-emerald"

除了我希望结果只包含匹配项。有没有办法用replace() 方法做到这一点?

【问题讨论】:

    标签: javascript regex regex-group


    【解决方案1】:

    是的,关键是要完整收集整个字符串数据,然后替换成想要的组:

    const regex = /.*\sversion\s(.*?)\s.*/gs;
    const str = `xml version 2.1.2-emerald https://www.example.com`;
    const subst = `$1`;
    
    // The substituted value will be contained in the result variable
    const result = str.replace(regex, subst);
    
    console.log('Substitution result: ', result);

    【讨论】:

      【解决方案2】:

      而不是replace,而是match,并提取第一个捕获的组。你也可以用(\S+)代替(.*?)\s

      const regex = /\sversion\s(\S+)/;
      const str = `xml version 2.1.2-emerald https://www.example.com`;
      const result = str.match(regex);
      console.log(result[1]);

      如果可能没有匹配,首先检查结果不是null

      const regex = /\sversion\s(.*?)\s/;
      const str = `foo bar`;
      const result = str.match(regex);
      if (result) {
        console.log(result[1]);
      }

      如果您希望完全匹配正是您要查找的内容,您可以使用lookbehind,尽管这仅适用于较新的浏览器,并且不是一个好的跨浏览器解决方案:

      const regex = /(?<=\sversion\s)\S+/;
      const str = `xml version 2.1.2-emerald https://www.example.com`;
      const result = str.match(regex);
      console.log(result[0]);

      【讨论】:

      • 完全匹配。 (从version 到模式末尾的\s
      猜你喜欢
      • 2015-11-11
      • 2018-12-13
      • 2022-01-14
      • 1970-01-01
      • 2012-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多