Get backreference name-based regex from index-based regex

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Get backreference name-based regex from index-based regex



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?




2 Answers
2



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


k


(?(<bracket>)



So, try:


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



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





work like a charm :) thank for your help!
– Tuyen Pham
Aug 8 at 7:33





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 ^(?<bracket>()?d+(?(bracket)))$
– Tuyen Pham
Aug 8 at 7:52



<


>


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





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 8 at 8:02



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 )


(?( name ) yes | no )



or



(?( number ) yes | no )


(?( 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






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS