从基于索引的正则表达式中获取反向引用基于名称的正则表达式

Get backreference name-based regex from index-based regex

我有这个正则表达式字符串:

^(\()?\d+(?(1)\))$

它将匹配以下字符串:

123
(1234)
1
(33)

但不会匹配以下字符串:

(123
123)

我想将基于索引的正则表达式转换为基于名称的正则表达式,但以下正则表达式似乎不起作用:

^(?<bracket>\()?\d+(?(\k<bracket>)\))$

第一个正则表达式字符串的等效基于名称的正则表达式是什么?

您需要 if 子句,而不是反向引用。 - \k 是反向引用。测试先前命名的子模式的语法是

(?(<bracket>)

所以,尝试:

^(?<bracket>\()?\d+(?(<bracket>)\))$

https://regex101.com/r/Oy9q1H/1

要测试命名组堆栈是否为空,您应该在括号内使用名称本身:

^(?<bracket>\()?\d+(?(bracket)\))$
                     ^^^^^^^^^ 

.NET regex demo

参见Conditional Matching Based on a Valid Captured Group

This language element attempts to match one of two patterns depending on whether it has matched a specified capturing group. Its syntax is:

(?( name ) yes | no )

or

(?( number ) yes | no )

where name is the name and number is the number of a capturing group, yes is the expression to match if name or number has a match, and no is the optional expression to match if it does not.

参见C# demo

var strs = new List<string> { "123", "(1234)", "1", "(33)", "(123", "123)"};
var rx = new Regex(@"^(?<bracket>\()?\d+(?(bracket)\))$");
    foreach (var s in strs)
        Console.WriteLine($"{s} => {rx.IsMatch(s)}");

输出:

123 => True
(1234) => True
1 => True
(33) => True
(123 => False
123) => False