简体   繁体   中英

String validation in java using regex

I have to validate a set of strings and do stuff with it. The acceptable formats are :

1/2
12/1/3
1/23/333/4

The code used for validation is:

if (str.matches("(\\d+\\/|\\d+){2,4}")) {
    // do some stuff
} else {
    // do other stuff
}

But it will match any integer with or without slashes, I want to exclude ones without slashes.. How can I match only the valid patterns?

It looks like you want to find number (series of one or more digits - \\d+ ) with one or more /number after it. If that is the case then you can write your regex as

\\d+(/\\d+)+

You can try

                                        (\d+/){1,3}\d+
digits followed by / one to three times----^^^^^^   ^^------followed by digit

Sample code:

System.out.println("1/23/333/4".matches("(\\d+/){1,3}\\d+")); // true
System.out.println("1/2".matches("(\\d+/){1,3}\\d+"));        // true
System.out.println("12/1/3".matches("(\\d+/){1,3}\\d+"));     // true

Pattern explanation:

  (                        group and capture to \1 (between 1 and 3 times):
    \d+                      digits (0-9) (1 or more times)
    /                        '/'
  ){1,3}                   end of \1
  \d+                      digits (0-9) (1 or more times )
\\b\\d+(/\\d+){1, 3}\\b

\\b is a word boundary. This will match all tokens with 1-3 slashes, with the slashes surrounded by digits and the token surrounded by word boundaries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM