Yassin Hajaj
Yassin Hajaj

Reputation: 21975

Java Regex : 4 Letters followed by 2 Integers

Regex beginner here.

Already visited the followings, none answers my question :

1, 2, 3, 4, 5, 6, etc.

I have a simple regex to check if a string contains 4 chars followed by 2 digits.

[A-Za-z]{4}[0-9]{2}

But, when using it, it doesn't matches. Here is the method I use and an example of input and output :

Input in a JPasswordField

Mypass85

Output

false

Method

public static boolean checkPass(char[] ca){
    String s = new String(ca);
    System.out.println(s); // Prints : Mypass85
    p = Pattern.compile("[A-Za-z]{4}[0-9]{2}");
    return p.matcher(s).matches();
}

Upvotes: 1

Views: 3045

Answers (2)

rgettman
rgettman

Reputation: 178253

Promoting a comment to an answer.

It doesn't match because "Mypass85" is 6 letters followed by 2 numbers, but your pattern expects exactly 4 letters followed by 2 numbers.

You can either pass something like "Pass85" to match your existing pattern, or you can get "Mypass85" to match by changing the {4} to {6} or to {4,} (4 or more).

Upvotes: 2

anubhava
anubhava

Reputation: 785008

Matcher#matches attempts to match full input. Use Matcher#find instead:

public static boolean checkPass(String s){
    System.out.println(s); // Prints : Mypass85
    p = Pattern.compile("[A-Za-z]{4}[0-9]{2}");
    return p.matcher(s).find();
}

Upvotes: 3

Related Questions