Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string is of a specific pattern [closed]

Tags:

java

regex

The user inputs any string and the program distinguishes whether the string is qualifying product ID or not.

The qualifying product IDs are any of string consists of two capitals and four numbers. (For example, "TV1523")

How can I make this program?

like image 769
schizoid322 Avatar asked Oct 27 '11 09:10

schizoid322


1 Answers

You should compare the string using a regular expression, for example:

str.matches("^[A-Z]{2}\\d{4}") will give you a boolean value as to whether it matches or not.

The regular expression works as follows:

^ Indicates that the following pattern needs to appear at the beginning of the string.
[A-Z] Indicates that the uppercase letters A-Z are required.
{2} Indicates that the preceding pattern is repeated twice (two A-Z characters).
\\d Indicates you expect a digit (0-9)
{4} Indicates the the preceding pattern is expected four times (4 digits).

Using this method, you can loop through any number of strings and check if they match the criteria given.

You should read up on regular expressions though, there are more efficient ways of storing the pattern if you are worried about performance.

like image 187
Ewald Avatar answered Oct 01 '22 23:10

Ewald