0

I want to validate an identification format using Java.

Examples: UWU/CST/14/0015 or UWU/IIT/14/0025

Here UWU is required, and one of CST or IIT must be present else it is invalid. After that it can have any two digits and then at least four digits in the last section. Please help me in solving this.

package validate2;

import java.util.*;
public class Validate2 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here
    Scanner a=new Scanner(System.in);
    String l=a.next();
    boolean x=l.matches("^uwu\\/\\w\\w\\w\\/\\d\\d\\/\\d\\d\\d\\d");

    if (x == false) {
        //JOptionPane.showMessageDialog(rootPane, "Enter a valid serviceNO");
        System.out.println("NO");
        //return false;
    } else {
        System.out.println("YES");
        //return true;
    }

}

}
2
  • Case sensitive ? Commented May 12, 2017 at 19:34
  • 1
    @Rahul yeas mate..help me to solve this Commented May 12, 2017 at 19:35

3 Answers 3

3

Regex:

^UWU\/(CST|IIT)\/\d{2}\/\d{4,}$
  • Ensures it starts with UWU
  • Ensures second part is either CST or IIT
  • Ensures the third part contains exactly 2 digits \d{2}
  • Ensures the last part contains 4 or more digits \d{4,}

Regex 101 Demo

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

2

You can try to use this regex (?i)UWU\/(CST|IIT)/\d{2}\/\d{4} :

String str = "UWU/CST/14/0015";
String regex = "(?i)UWU\\/(CST|IIT)/\\d{2}\\/\\d{4}";
System.out.println(str.matches(regex));

  1. (?i) : will accept any upper or lower case
  2. UWU : start with UWU
  3. (CST|IIT) : followed by CST or IIT
  4. \d{2} : followed by 2 degits
  5. \d{4} : followed by 4 degits

Comments

1

Well instead of this long regex ^uwu\\/\\w\\w\\w\\/\\d\\d\\/\\d\\d\\d\\d

Here is the simplest one.

Regex: ^UWU\/(?:CST|IIT)\/\d+\/\d+$

Explanation: Starting with literal UWU followed by / followed by either CST or IIT followed by / multiple digits then / then multiple digits.

To restrict no of digits use {n,m} where n is minimum no and m is max.

Regex101 Demo

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.