Reputation: 307
I have a field, where a user can search for something. They should be able to search for ^[0-9a-zA-Z*]$
.
But it is not possible to search just for the character *
(wildcard). There must be at least one other letter or number. a* or *a or 1* or *1
is valid.
So there must be at least one number/letter unequal *
for a valid search.
I think it should be realizable with the if/then/else condition. Here is my attempt!
"^(?(?=[*])([0-9a-zA-Z:\]{1,})|([0-9a-zA-Z:\*]*))$"
if character = *
then [0-9a-zA-Z:\]{1,} = user has to enter at least one (or more) characters of the group
else = [0-9a-zA-Z:\*]* = user has to enter 0 or more characters of the group
But it doesn't work...
Upvotes: 1
Views: 224
Reputation: 626690
You may use
^[0-9a-zA-Z*]*[0-9a-zA-Z][0-9a-zA-Z*]*$
See the regex demo
This regex will match zero or more letters/digits/asterisks, then an obligatory letter or digit, and then zero or more letters/digits/asterisks.
Alternatively, you can require a string to have at least 1 letter or digit:
^(?=.*[0-9a-zA-Z])[0-9a-zA-Z*]+$
See another demo. The ^(?=.*[0-9a-zA-Z])
positive lookahead will require a letter or a digit after zero or more any characters but a newline. It can also be written as ^(?=.*\p{Alnum})[\p{Alnum}*]+$
(with double escaping backslash in Java).
String rx = "(?=.*\\p{Alnum})[\\p{Alnum}*]+";
System.out.println("****".matches(rx)); // FALSE
System.out.println("*a**".matches(rx)); // TRUE
Upvotes: 1