Is it possible to create regular expressions based on string characters?
Let me explain with an example, I am looking for a regular expression that validates that in a string, if the first digit is 0, the second cannot be. But the rest of the digits can be the number they want, examples:
0102 - Bien
0123 - Bien
0012 - Mal
But, on the contrary, if the string begins with a number other than 0, that second digit can be 0 or the number you want, examples:
1234 - Bien
1000 - Bien
1089 - Bien
Let's see if you can give me a hand with the validation based on a digit, because I don't finish finding the key.
With this we create two possible match groups:
Of course this regular expression could be simplified:
So starting with
0
is optional, but if you do, the second number cannot be a0
, since the group[1-9]
does not allow it.(?:..)
Allows you to create a group but without capturing it. the idea is that everything that is not the0
initial one is optional (which is why after this non-capture group there is a question mark: . In addition, the by(?:..)?
have been replaced to match 0 or more occurrences instead of necessarily one.+
*
This expression, like the first, can be easily simplified:
Based on the comments, the following can be deduced:
^0$
^0?[1-9]\d*$
Grouping the 2 cases we would have:
^(0|0?[1-9]\d*)$
Important Note : If what is being evaluated is a string that internally contains the patterns to locate, for example: 0 00 0102 0123 0012 03 Casa 120 Puerta 2516 Caracas
In this case, it is delimited by blocks of words, leaving the regular expression:
\b(0|0?[1-9]\d*)\b
Remember to add the global and multi-line parameters in case the string has multiple lines.
Reading your question literally, the answer is simpler than it seems:
That is all. If it matches
^00
, then it's wrong, if it doesn't, it's ok. It's just a matter of negating the final result of the regex.Of course, if you are also interested in validating that it is indeed a number, I would go with linuxexp's answer that solves it.