c# - Regular expression with conditional repeat -


i have following regular expression:

^((_[a-za-z0-9]|[a-za-z])+((?<bracket>\[)[0-9]+(?<-bracket>\])(?(bracket)(?!)))?)$ 

i want repeat if there dot (.)

i know can repeat expression adding 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 want know if there better way, without copying initial part.

background:

i need access machine micrologix 5000 uses tag based addressing. in c# application, want validate user input address.

allowed:

  • dog.tail
  • dogs[0].tail.ismoving

not allowed:

  • dog.
  • dogs[0].

you can use recursion. see this:

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

however, 2 steps less efficient attempted regex, optimal case. recursion can used here increase readability, not recommended practice.


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -