RegEx 用于匹配除开始和结束处的重复字符之外的所有内容

RegEx for matching everything except a repeating char at start and end

我有一个字符串模式,示例如下。

AA4grgrsragrga4334grAA

AAA4323425AAA

AAAAAA%%%AAAAAA

前导“A”和尾随“A”总是成对出现。

我试过:

A+.+A+

不知道如何在 REGEX 中配对前导 A 和尾随 A。

捕获组中的初始As,然后重复匹配后面跟非A的任何字符,然后再次向后引用第一个组,后面跟字符串的结尾:

^(A+).*[^A]$

https://regex101.com/r/81ge2k/2

如果A只会出现在字符串的开头和结尾,可以使用负数字符集代替:

^(A+)[^A]*$

如果输入字符串应该跨越整行,请确保使用 start-of-string 和 end-of-string 锚点,否则模式可以匹配不匹配的 As。

如果您还想匹配 AA 或 AAAAAA 以及 AAteAstAA 等字符串开头和结尾的成对 A,您可以使用交替:

^(A+)(?:[^A].*[^A]|[^A])?$

关于图案

  • ^ 字符串开头
  • (A+)在第一组匹配1+个A中捕获
  • (?:非捕获组
    • [^A].*[^A] 不匹配 A,0+ 次除换行符外的任何字符,然后再次不匹配 A
    • |
    • [^A]匹配不是A
  • )? 关闭非捕获组并使其可选
  • </code> 向后引用组 1</li> <li><code>$ 字符串结束

Regex demo

如果AAA也能匹配你可以用

^(A+)(?:[^A].*[^A]|.)?$

Regex demo

This expressionA+ 之间有一个简单的捕获组,从左到右滑动中间的每个 non-A 个字符:

A+([^A]*)A+


如果你想捕获A+,你可以简单地用两个捕获组()包裹它们,类似于this expression

(A+)([^A]*)(A+)


如果您不想匹配 A 字符,那么您可以简单地将它们从 the expression:

中删除
[^A]*

但是,如果中间有A,这将不匹配,需要修改。


正则表达式描述图

此图将表达式可视化,如果需要,您可以在此 link 中测试其他表达式:

JavaScript 测试

const regex = /(A+)([^A]*)(A+)/gm;
const str = `AA4grgrsragrga4334grAA
AAA4323425AAA
AAAAAA%%%AAAAAA`;
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}`);
    });
}

(A+)([^A]*)(A+) 的基本性能测试

此 JavaScript 片段 returns 运行一百万次 for 循环以提高性能。

const repeat = 1000000;
const start = Date.now();

for (var i = repeat; i >= 0; i--) {
 const string = 'AAAAAAAAAanyThingElse4grgrsragrga4334grAAAA';
 const regex = /(A+)([^A]*)(A+)/gm;
 var match = string.replace(regex, "\nGroup #1: \nGroup #2: \nGroup #3: \n");
}

const end = Date.now() - start;
console.log("YAAAY! \"" + match + "\" is a match  ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test.  ");

A+([^A]*)A+

的基本性能测试

const repeat = 1000000;
const start = Date.now();

for (var i = repeat; i >= 0; i--) {
 const string = 'AAAAAAAAAanyThingElse4grgrsragrga4334grAAAA';
 const regex = /A+([^A]*)A+/gm;
 var match = string.replace(regex, "Group #1: ");
}

const end = Date.now() - start;
console.log("YAAAY! \"" + match + "\" is a match  ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test.  ");