I have a regular expression I need to implement. The rules are
2 digits followed by
2 .. or 2 -- or 2 __ followed by 2 digits
it cannot be empty
it cannot have only one pair (i.e. 01)
The string can be up to 1000 characters in length.
i.e.,
01..02--03 or
01..01 or
01--02--03--04--05..06 and so on
Here is how I would do it:
\d{2}(?:(?:[.]{2}|-{2}|_{2})\d{2})+
Explanation: Two digits, followed by one or more occurrences of two of the same character consisting of either a period, a hyphen, or an underscore, followed by two more digits.
If you need to anchor this, you can add a ^
at the front and a $
at the end.
The reason I prefer the use of {2}
instead of spelling things out (i.e., repeating the same symbol) is that it allows you to increase the number. As the number gets large, counting the number of repeated symbols would get more and more difficult.
Also, depending on your font and screen size, some symbols can get visually merged into one longer symbol making it difficult to ascertain how many of them are in sequence. The undescore character is a prime example of this, consider: _____
How many underscores is that? Compare and contrast that with this expression: _{5}
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