Same number of occurrences before and after characters

I am trying to implement a regex to test code consisting of two numbers that should be the same length. Here is an example of the possible values:

  • sixteen
  • 12 67
  • 123 678
  • 1234 6789
  • 12345 67890

I have a limit of 5 digits, so the only solution I found is the following:

^(
   ([0-9][ ][0-9])|
   ([0-9]{2}[ ][0-9]{2}) |
   ([0-9]{3}[ ][0-9]{3}) |
   ([0-9]{4}[ ][0-9]{4}) |
   ([0-9]{5}[ ][0-9]{5})
)$

Any suggestion or alternative is accepted. After a day of thinking, this solution is the only way to perform this test, but I know that it is greedy.

+4
source share
1 answer

In .NET, since you use this regex flavor, you can use balancing constructions :

^(?<o>\d){1,5} (?<-o>\d){1,5}(?(o)(?!))$

regex

. .

  • ^ -
  • (?<o>\d){1,5} - 1 5 , o, Captures
  • - space ( , RegexOptions.IngorePatternWhitespace)
  • (?<-o>\d){1,5} - 1 5 , o
  • (?(o)(?!)) - , o. ((?(o))), ( (?!) )
  • $ - .

, .

+1

Source: https://habr.com/ru/post/1649272/


All Articles