regular expression with alphanumeric with all special chars excpet with %

Viewed 52

regular expression with alphanumeric with all special chars excpet with %

Length of string must be 1 to 12.

trying this way (as regex), but this is allowing % also.

[[^=][\w\S][^-]]{1,13}   

example my input string (itemValue) for above pattern, should give false: test%t1z

            Pattern pattern = Pattern.compile(regexStr);
            Matcher matcher = pattern.matcher(itemValue);

            if(matcher.matches()){
                flag = true;
            }
1 Answers

You can use either of:

String regexStr = "[^%]{1,12}";    # If whitespaces are allowed
String regexStr = "[^%\\s]{1,12}"; # If whitespaces are disallowed

Note that Pattern#matches requires a full string match, thus, there is no need adding anchors like \A/\z to the regex pattern.

Details

  • [^%]{1,12} - matches any one to twelve chars other than %
  • [^%\s]{1,12} - matches one to twelve chars other than % and whitespace

See the Java demo:

List<String> strs = Arrays.asList("abc123#67812", "abc123%67812", "abc123#678120");
String regexStr = "[^%\\s]{1,12}";
Pattern pattern = Pattern.compile(regexStr);

for (String itemValue : strs) {
    Matcher matcher = pattern.matcher(itemValue);
    System.out.println("\"" + itemValue + "\": " + matcher.matches());
}

// => "abc123#67812": true
//    "abc123%67812": false
//    "abc123#678120": false
Related