Home > other >  How to check if digit is at specific place in combination with other regexes
How to check if digit is at specific place in combination with other regexes

Time:11-25

In a method that uses Pattern.matches, I need a correct regex. The method is supposed to return true if:

  • pwd starts with a capital letter followed by three lower case letters
  • pwd contains exactly one digit, at position 6 of the string
  • pwd contains at least 8 characters

I get the first and last requirement fulfilled but cannot include the second one (only one digit at sixth place).

private boolean validPass(String pwd)
{
    return Pattern.matches("^[A-Z]{1}[a-z]{3}.{8,}$", pwd);
}

How to include this condition "pwd contains exactly one digit, at position 6 of the string" in the method above?

CodePudding user response:

Here's a changed pattern that works.

public static void main( String[] args ){
    //String original = "^[A-Z]{1}[a-z]{3}.{8,}$";
    String s = "^[A-Z][a-z]{3}[^0-9][0-9][^0-9]{2,}$";
    Pattern p = Pattern.compile( s );
        
    String GOOD_PWD = "PabcO5jjfjj";
    String NOT_LONG_ENOUGH = "PabcO5j";
    String NOT_NUM_AT_6 = "PabcOTTggj";
    List<String> pwds = Arrays.asList( GOOD_PWD, NOT_LONG_ENOUGH, NOT_NUM_AT_6 );

    for( String pwd : pwds ) System.out.println( pwd   ": "   p.matcher( pwd ).matches() );  
}

Explanation of ^[A-Z][a-z]{3}[^0-9]{1}[0-9][^0-9]{2,}$:

  • [A-Z]: First character should be capital (you had done this already)
  • [a-z]{3}: Next 3 characters should be small letters (you had done this already)
  • [^0-9]: One non-numeric character to fill the space till position 6
  • [0-9]: One digit at position 6
  • [^0-9]{2,}: Minimum 2 non-numeric characters (2 because we already have 6 till here. Non-numeric because we want digits only at position 6.)
  • Related