除特殊情况外如何获取组匹配模式

How to get groups matching pattern except special cases

我试图从除 <:randomtext:123><a:randomtext:123> 情况下的字符串中获取所有 :randomtext: 模板,并将它们替换为另一个字符串。我怎样才能得到所有这些组?

尝试

[^<](:\w+?:)

这是我的 demo

我猜这里我们只是想要一个简单的表达式,

(?:<.*?)(:.*?:)(?:.+?>)

替换成我们想要的任何东西。

Demo

const regex = /(?:<.*?)(:.*?:)(?:.+?>)/gmi;
const str = `:fra: :fra: <:fra:12312312> <a:fra:!232131> :fra::fra:
Some text:fra: Hello:fra::fra::fra: :fra:`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

对于您的示例数据,您可以匹配不需要的内容并捕获需要的内容。您可以在至少包含 :

的括号之间进行捕获
<.*?:.*?>|(:\w+:)

Regex demo

或者如果您不想匹配中间的括号,您可以使用否定字符 class [^<>] 来匹配而不是左括号或右括号。

<[^<>]*:[^<>]*>|(:\w+:)
  • < 匹配 < 字符
  • [^<>]* 取反字符class,匹配不<或>0+次
  • : 匹配:
  • [^<>]* 取反字符class,匹配不<或>0+次
  • > 匹配 > 字符
  • |
  • (:\w+:) 在第 1 组中捕获匹配 1+ 个单词字符:

Regex demo

const regex = /<[^<>]*:[^<>]*>|(:\w+:)/gm;
const str = `:fra: :fra: <:fra:12312312> <a:fra:!232131> :fra::fra:
Some text:fra: Hello:fra::fra::fra: :fra:`;
let m;

while ((m = regex.exec(str)) !== null) {
  // This is necessary to avoid infinite loops with zero-width matches
  if (m.index === regex.lastIndex) {
    regex.lastIndex++;
  }
  if (undefined !== m[1]) {
    console.log(m[1]);
  }
}

如果你想 replace 匹配 :fra:new 你可以切换捕获组并使用回调替换。

const regex = /(<[^<>]*:[^<>]*>)|:\w+:/gm;
let str = `:fra: :fra: <:fra:12312312> <a:fra:!232131> :fra::fra:
Some text:fra: Hello:fra::fra::fra: :fra:`;

str = str.replace(regex, function(m, g1) {
  return undefined === g1 ? "new" : m;

});
console.log(str);