Danith Kumarasinghe
Danith Kumarasinghe

Reputation: 201

Validate a text and number format using Regex in Java

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;
    }

}

}

Upvotes: 0

Views: 231

Answers (3)

degant
degant

Reputation: 4981

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!

Upvotes: 3

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59960

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

Upvotes: 2

Rahul
Rahul

Reputation: 2738

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

Upvotes: 1

Related Questions