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 :
- 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?
^(?:\?*[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.
Here is an alternative regex that is faster, as revo suggested in the comments:
^(?:\?*[a-zA-Z\d]){2}[a-zA-Z\d?]*\*?$