I need a regex to match a string that:
0-9
and spacesMatches:
11 11111 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1
No matches:
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?
You can use alternation (|) operator to combine multiple patterns for your regexp. But in case you have various input and you will have to convert them to instance of Date from a string. Then you must follow in a sequence and validate the input one by one.
to combine two expressions or more, put every expression in brackets, and use: *? This are the signs to combine, in order of relevance: ?
$ means "Match the end of the string" (the position after the last character in the string).
Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.
Yes it can be done in one regex:
^(\d)(?:\1| )*\1$
Rubular link
Explanation:
^ - 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With