How to check if a string has a specific pattern

The user enters any string, and the program distinguishes whether the string is a product identifier or not.

Qualification product identifiers are any string consisting of two capitals and four numbers. (For example, "TV1523")

How can I make this program?

+6
source share
3 answers

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

str.matches("^[AZ]{2}\\d{4}") will give you a boolean 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. [AZ] Indicates that the uppercase letters AZ are required. {2} Indicates that the preceding pattern is repeated twice (two AZ 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 scroll through any number of lines and check if they meet the specified criteria.

You should read regular expressions, but there are more efficient ways to store a pattern if you are worried about performance.

+25
source

You should study regular expressions more closely. A tutorial, for example, is here regular-expressions.info .

An example of your template might be

 ^[AZ]{2}\d{4}$ 

you can see here at Regexr.com , a good place to test regular expressions on the Internet.

Here is the java regex tutorial there you can see what you call them in Java.

+4
source
 public static void main(String[] args) throws Exception { String id = "TV1523"; BufferedReader br = new BufferedReader((new InputStreamReader(System.in))); String tocompare = br.readLine(); if(tocompare.equals(id)) { //do stuff 

something like this, except that you can make a wand to include readLine () in a try catch instead of: x

0
source

Source: https://habr.com/ru/post/900187/


All Articles