Regular expression with conditional repetition
I have the following regex:
^((_[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 an expression like this by adding a 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 original part.
Background:
I need to access a Micrologix 5000 machine that uses addressing. In a C # application, I want to validate that the user is entering a good address.
Allowed:
-
Dog.Tail
-
Dogs[0].Tail.IsMoving
Is not allowed:
-
Dog.
-
Dogs[0].
+3
source to share
1 answer
You can use recursion. See this:
^((_[a-zA-Z0-9]|[a-zA-Z])+((?<bracket>\[)[0-9]+(?<-bracket>\])(?(bracket)(?!)))?)(\.\1)*$
^^
-
\1
recurses the first submatrix in the first capture group( )
.
However, this is two steps less efficient than your programmed regex, which is optimal for this case. Recursion can be used here to improve readability, but is not recommended.
+2
source to share