javaregexwildcardwhitespace

Java Regex match space before or after characters


I try to have a regex validating an input field.

This question is the continuation of this question but I made a mistake and the question changed a bit so I created a new one.

Here is my java regex :

^(?:\?*[a-zA-Z\d]){2}[a-zA-Z\d?]*\*?$

Demo

What I'm tying to match is :

So for exemple :

  • abcd = OK
  • ?bcd = OK
  • ab?? = OK
  • ab*= OK
  • ab?* = OK
  • ??cd = OK
  • ab cd = OK
  • *ab = NOT OK
  • a ? b =NOT OK
  • ??? = NOT OK
  • ab? cd = NOT OK
  • ab ?d = NOT OK
  • ab * = NOT OK
  • abcd = NOT OK (space at the begining)

As i've asked in the fisrt question, no white space at all are allowed in my regex now but that's not what I want and I'm a bit lost can you help me please?


Solution

  • You may use

    ^(?!\s)(?!.*\s[*?])(?!.*[*?]\s)(?:[?\s]*[a-zA-Z0-9]){2}[a-zA-Z0-9?\s]*\*?$
    

    See the regex demo.

    Usage note: if you use it with Java's .matches() method, the ^ and $ can be removed from the pattern. Remember to double escape backslashes in the string literal.

    Details