Can this be done in one regex?
I need a regex to match a string that:
- has only digits 0-9 and spaces
- all digits must be same
- should have at-least 2 digits
- should start and end with digits
11 11111 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1
1 has only one digit 11111 has space at the end 11111 has space at beginning 12 digits are different 11: has other character
I know regex for each of my requirement. That way I'll use 4 regex tests. Can we do it in one regex?
Yes it can be done in one regex:
^ - Start anchor ( - Start parenthesis for capturing \d - A digit ) - End parenthesis for capturing (?: - Start parenthesis for grouping only \1 - Back reference referring to the digit capture before | - Or - A literal space ) - End grouping parenthesis * - zero or more of previous match \1 - The digit captured before $ - End anchor