javaregex

Pattern matching for validating the input


I have to validate the input as

I am trying to build as this.

final Pattern pattern =
            Pattern.compile("^[a-zA-Z~][a-zA-Z*]*$", Pattern.CASE_INSENSITIVE);

final Matcher matcher = pattern.matcher(this.mainStaOrgBO.getStaOrgCode());
        final boolean specialCharCheck = matcher.find();
        if (specialCharCheck) {
}

Solution

  • How about:

    ^[a-zA-Z~][a-zA-Z*]{1,4}[a-zA-Z]*$
    

    Explanation:

    ^                   : start of string
        [a-zA-Z~]       : First char can be letter or ~
        [a-zA-Z*]{1,4}  : char 2 to 5 can be letter or *
        [a-zA-Z]*       : rest of string only letter
    $                   : end of string.