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?]*\*?$
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?
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
^
- start of string (?!\\s)
- no whitespace is allowed immediately to the right (at the start of the string) (?!.*\\s[*?])
- no whitespace is allowed after any 0+ chars, as many as possible, before *
or ?
(?!.*[*?]\\s)
- no whitespace is allowed after any 0+ chars, as many as possible, after *
or ?
(?:[?\\s]*[a-zA-Z0-9]){2}
- two sequences of
[?\\s]*
- 0 or more ?
or/and whitespaces [a-zA-Z0-9]
- an alphanumeric char [a-zA-Z0-9?\\s]*
- 0 or more letters, digits, ?
or whitespaces \\*?
- an optional ?
char $
- end of the string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.