Reputation: 852
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].
Upvotes: 3
Views: 210
Reputation: 11041
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.
Upvotes: 2