Issue in Regex for set for characters, fixed length and paces at beginning and ending of a string

Golu :

Initially, I had a requirement that I should check whether a given string follows following two patterns.

  • "^(.{1,5})?$" --It is meant to check whether the string is of length up to 5 characters
  • "[!-~]|([!-~][ -~]*[!-~])" -It is meant to signify that String does not start or end with white spaces.

Earlier we were to give two different messages when the string would not match any, so I handled like below :

    Pattern pattern1 = Pattern.compile("^(.{1,5})?$");
    Pattern pattern2 = Pattern.compile("[!-~]|([!-~][ -~]*[!-~])");
    Matcher matcher1=pattern1.matcher(" verify");
    Matcher matcher2 = pattern2.matcher("verify");
    System.out.println("Message1 - " + matcher1.matches());
    System.out.println("Message2 - " + matcher2.matches());

But now the requirement is that we need to : --We need to club both the above patterns BUT

--Also include that the string can contain the following characters $, #,@ other than letters, number

--And give one single message.

I looked on many similiar questions asked like: regex for no whitespace at the begining and at the end but allow in the middle and https://regex101.com/ to make a single regex like :

Pattern pattern3=Pattern.compile(
  "^[^\\\s][[-a-zA-Z0-9-()@#$]+(\\\s+[-a-zA-Z0-9-()@#$]+)][^\\\s]{1,50}$");

But the regex is not working correctly. If I provide a string with a character other than mentioned in the regex like '%' it should have failed but it passed.

I am trying to figure out that what is problem in the above regex or any new regex which can fulfil the need.

@edit to be more clear: Valid input : "Hell@"

Invalid input : " Hell" (have whitepace @beginning)

Invalid input : "Hell%" conatins not required char '%'

anubhava :

You may use this regex:

^(?!\s)[a-zA-Z\d$#@ ]{1,5}(?<!\s)$

RegEx Demo

RegEx Details:

  • ^: Start
  • (?!\s): Negative lookahead, don't allow space at start
  • [a-zA-Z\d$#@ ]{1,5}: Allow these character between 1 to 5 in length
  • (?<!\s): Negative lookbehind, don't allow space before end
  • $: End

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=153115&siteId=1