regular expression (for 3 words) with alphanumeric with all special chars except with % -

Viewed 43

regular expression with alphanumeric with all special chars except with % - in the words.

it is 3 word separated with hyphen. first and second word can allow anything except % - Third word is only digits

first word

  1. not be empty (i.e. not a simple white space). but it can allow spaces in between.
  2. can not contain % and -
  3. length must be 1 to 10

second word

  1. not be empty (i.e. not a simple white space). but it can allow spaces in between
  2. can not contain % and -
  3. length must be 1 to 12

third word

  1. not be empty (i.e. not a simple white space)
  2. only digits allowed
  3. length must be 4 to 9

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

[[^%\-\s]]{1,10}[-]{1}[[^%\-\s]]{1,12}[-]{1}[\d]{4,9}  

allowed strings:

"1sAS-c$AS-01238"
"t t-c:t-012345678"
"t$t-c 2:t-012345678"

Not allowed strings:

"1sA%S-c$AS-01238"   (because this contains % in the first word)
" -c:t-01235678"     (because this contains only space in the first word)
"t$t- -01234578"     (because this contains only space in the 2nd word)
"t-$t-check-012378"  (because this contains more hypens)

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

String regexStr = "(?!\\s+-)[^%-]{1,10}-(?!\\s+-)[^%-]{1,12}-\\d{4,9}";

See the regex demo.

Details:

  • \A - start of string (implicit when the regex is used with matches())
  • (?!\s+-) - immediately to the right, there should not be one or more whitespaces and then a - char
  • [^%-]{1,10} - one to ten chars other than % and - ([^%\n-] does not allow to match a newline in the demo)
  • - - a hyphen
  • (?!\s+-) - immediately to the right, there should not be one or more whitespaces and then a - char
  • [^%-]{1,12} - one to twelve chars other than % and -
  • - - a hyphen
  • \d{4,9} - four to nine digits
  • \z - end of string (implicit when the regex is used with matches()).
Related