How to make RegEx for a "serial" number format?

4

How to do RegExp in the following format:

2015.1.123.5432

Does anyone have any ideas?

    
asked by anonymous 07.08.2015 / 00:18

1 answer

6

I think it's something like:

\d+\.\d+\.\d+\.\d+

or else:

\d{4}\.\d{1}\.\d{3}\.\d{4}
  • The \d represents any numeric value of 0-9
  • The {...} represents the number of characters represented by what is before {
  • The + means that it will look for the character before the plus sign + until it finds the next one (which in this case is . ).

Let's suppose that in 2015.1.123.5432

  • 2015 will always be 4 digits
  • 1 will be 1 to 2 digits
  • 123 will be 3 to 4 digits
  • 5432 will be 4-digit "unlimited"

So you should do the regex like this:

\d{4}\.\d{1,2}\.\d{3,4}\.\d{4,}
  • {1,2} means that you will look for numbers like 1, 2, 13, 99. But you will ignore 100 or greater
  • {3,4} means that you will look for numbers like 123, 200, 998, 9900. But you will ignore numbers smaller than 100 and greater than 9999.
  • {4,} will only accept numbers from 1000 upwards.

If the serial number has spaces, you can use replaceAll to remove them before using RegEx or later (if you use regex to extract data from a text), like this:

String minhaSrt = " 2015 .1 .123 .5432 ";
minhaStr = minhaStr.replaceAll(" ", "");

Or use \s that will remove spaces and tabs:

String minhaSrt = " 2015 .1 .123 .5432 ";
minhaStr = minhaStr.replaceAll("\s", "");
    
07.08.2015 / 00:25