Search code examples
javaregexmetacharacters

Java Regex with "Joker" characters


I try to have a regex validating an input field. What i call "joker" chars are '?' and '*'. Here is my java regex :

"^$|[^\\*\\s]{2,}|[^\\*\\s]{2,}[\\*\\?]|[^\\*\\s]{2,}[\\?]{1,}[^\\s\\*]*[\\*]{0,1}"

What I'm tying to match is :

  • Minimum 2 alpha-numeric characters (other than '?' and '*')
  • The '*' can only appears one time and at the end of the string
  • The '?' can appears multiple time
  • No WhiteSpace at all

So for example :

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

I've made the regex a bit complicated and I'm lost can you help me?


Solution

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

    Explanation:

    The regex asserts that this pattern must appear twice or more:

    \?*[a-zA-Z\d]\?*
    

    which asserts that there must be one character in the class [a-zA-Z\d] with 0 to infinity questions marks on the left or right of it.

    Then, the regex matches \*?, which means an 0 or 1 asterisk character, at the end of the string.

    Demo

    Here is an alternative regex that is faster, as revo suggested in the comments:

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

    Demo