How to make Regex to a "serial" number format?

Asked

Viewed 317 times

4

How to make Regexp of the following format:

2015.1.123.5432

Does anyone have any idea?

  • Danilo noticed that he deleted his other question, I think I could have waited, I even opened a question in the meta chance want to participate http://meta.pt.stackoverflow.com/q/4221/3635 - If you want to join the chat also welcome: http://chat.stackexchange.com/rooms/11910/estouro-de-pilha

1 answer

6


I believe it’s something like:

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

or else:

\d{4}\.\d{1}\.\d{3}\.\d{4}
  • The \d represents any numerical 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 sign more + even finds the next one (which in this case is the .).

Let’s support 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 digits to "unlimited"

Then you should do the regex like this:

\d{4}\.\d{1,2}\.\d{3,4}\.\d{4,}
  • {1,2} it means that you will look for numbers like 1, 2, 13, 99. but you will ignore 100 or higher
  • {3,4} means you will look for numbers like 123, 200, 998, 9900. But you will ignore numbers smaller than 100 and larger 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 using regex to extract data from a text), thus:

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

Or use the \s that will remove spaces and tabs:

String minhaSrt = " 2015 .1 .123 .5432 ";
minhaStr = minhaStr.replaceAll("\s", "");
  • Know if you can skip the white space if the string has space?

  • 2014.1.444.1254 ; Name Of Person

Browser other questions tagged

You are not signed in. Login or sign up in order to post.