我有一个字段,用户可以在其中搜索某些内容。他们应该能够搜索^[0-9a-zA-Z*]$
.
但是不可能只搜索字符*
(通配符)。必须至少有一个其他字母或数字。 a* or *a or 1* or *1
是有效的。
因此,必须至少有一个数字/字母不等*
才能进行有效搜索。
我认为它应该可以通过 if/then/else 条件来实现。这是我的尝试!
"^(?(?=[*])([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
但它不起作用...
^[0-9a-zA-Z*]*[0-9a-zA-Z][0-9a-zA-Z*]*$
查看正则表达式演示
此正则表达式将匹配零个或多个字母/数字/星号,然后是必填字母或数字,然后是零个或多个字母/数字/星号。
或者,您可以要求字符串至少包含 1 个字母或数字:
^(?=.*[0-9a-zA-Z])[0-9a-zA-Z*]+$
查看另一个演示。^(?=.*[0-9a-zA-Z])
正面前瞻将需要零个或多个字符后面的字母或数字,但换行符除外。它也可以写成^(?=.*p{Alnum})[p{Alnum}*]+$
(在 Java 中使用双转义反斜杠)。
Java演示:
String rx = "(?=.*\p{Alnum})[\p{Alnum}*]+";
System.out.println("****".matches(rx)); // FALSE
System.out.println("*a**".matches(rx)); // TRUE