3

I have this regex string:

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

It will match following strings:

123
(1234)
1
(33)

But will not match following strings:

(123
123)

I would like to convert the index-based regex to name-based regex, but following regex seem don't work:

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

What is equivalent name-based regex for the first regex string?

NoName
  • 7,940
  • 13
  • 56
  • 108

2 Answers2

2

You want an if clause, not a backreference. - \k is a backreference. The syntax to test for a previously named subpattern is

(?(<bracket>)

So, try:

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

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

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • I checked again and see that in c# you need to remove `<` and `>` characters in the if condition to make it work. The final regex is `^(?\()?\d+(?(bracket)\))$` – NoName Aug 08 '18 at 07:52
  • Regex101 does not support .NET regex syntax. It can only show how a regex might work, but cannot be used as a proof the regex will work in the target environment. – Wiktor Stribiżew Aug 08 '18 at 08:02
2

To test if a named group stack is not empty, you should use the name itself inside parentherses:

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

See the .NET regex demo

See the 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.

See the 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)}");

Output:

123 => True
(1234) => True
1 => True
(33) => True
(123 => False
123) => False
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563