Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression with conditional repeat

Tags:

c#

.net

regex

I have the following regular expression:

^((_[a-zA-Z0-9]|[a-zA-Z])+((?<bracket>\[)[0-9]+(?<-bracket>\])(?(bracket)(?!)))?)$

I want this to repeat if there is a dot (.)

I know I can repeat the expression like this adding the dot (.)

^((_[a-zA-Z0-9]|[a-zA-Z])+((?<bracket>\[)[0-9]+(?<-bracket>\])(?(bracket)(?!)))?)(\.((_[a-zA-Z0-9]|[a-zA-Z])+((?<bracket>\[)[0-9]+(?<-bracket>\])(?(bracket)(?!)))?))*$

But I want to know if there is a better way, without copying the initial part.

Background:

I need to access a machine Micrologix 5000 which uses tag based addressing. In a C# application, I want to validate that the user input a good address.

Allowed:

  • Dog.Tail
  • Dogs[0].Tail.IsMoving

Not Allowed:

  • Dog.
  • Dogs[0].
like image 355
Calimero100582 Avatar asked Aug 12 '26 17:08

Calimero100582


1 Answers

You can use recursion. See this:

^((_[a-zA-Z0-9]|[a-zA-Z])+((?<bracket>\[)[0-9]+(?<-bracket>\])(?(bracket)(?!)))?)(\.\1)*$
                                                                                    ^^
  • \1 recurses the first sub-pattern within the first capturing group ( ).

However, this is two steps less efficient than your attempted regex, which is optimal for this case. Recursion can be used here to increase its readability, but is not the recommended practice.

like image 105
Unihedron Avatar answered Aug 15 '26 07:08

Unihedron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!