Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression: 2 digits followed by .. or -- or __ followed by 2 digits

Tags:

regex

format

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
like image 688
MikeTWebb Avatar asked Dec 12 '22 08:12

MikeTWebb


1 Answers

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}

like image 66
Michael Goldshteyn Avatar answered Jan 31 '23 08:01

Michael Goldshteyn