Deep
Deep

Reputation: 959

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

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

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 '%'

Upvotes: 2

Views: 85

Answers (2)

anubhava
anubhava

Reputation: 786261

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

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522752

Here is a pattern which should meet your two requirements:

^\S(?:.{0,3}\S)?$

This says to match:

\S        an initial non whitespace character
(
    .{0,3}    zero to three of any character (whitespace or non whitespace)
    \S        a mandatory ending whitespace character
)?        the entire quantity optional

Demo

Upvotes: 0

Related Questions