0

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?

5
  • 3
    Like what "other cases"? Give us the cases it matches when it shouldn't. Commented Aug 19, 2014 at 13:31
  • Do you need the digits to be consecutive? Commented Aug 19, 2014 at 13:32
  • It will match any integer with or without slashes, I want to exclude ones without slashes. Commented Aug 19, 2014 at 13:33
  • 1
    @BinoyBabu see Pshemo's answer then. Commented Aug 19, 2014 at 13:34
  • @Mena no, digits need not be consecutive Commented Aug 19, 2014 at 13:34

3 Answers 3

3

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+)+
Sign up to request clarification or add additional context in comments.

Comments

1

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 )

Comments

0
\\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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.