我目前正在使用以下正则表达式:
^[a-zA-Z]{0,}(\\*?)?[a-zA-Z0-9]{0,}
检查字符串是否以字母字符开头、以字母数字字符结尾,并且在字符串中的任何位置都有星号 (*),但最多只能出现一次。这里的问题是,如果给定的字符串以数字开头但没有 * 仍然可以通过,那么它应该会失败。我怎样才能修改正则表达式来使这种情况失败?
例如。
TE - pass *TE - pass TE* - pass T*E - pass *9TE - pass *TE* - fail (multiple asterisk) 9E - fail (starts with number)
编辑: 抱歉,我们进行了较晚的编辑,但我还需要确保字符串不超过 8 个字符,我可以将其也包含在正则表达式中吗?或者我应该在正则表达式验证后检查字符串长度?
最佳答案
这通过了你的例子:
"^([a-zA-Z]+\\*?|\\*)[a-zA-Z0-9]*$"
It says:
start with: [a-zA-Z]+\\*? (a letter and maybe a star)
| (or)
\\* a single star
and end with [a-zA-Z0-9]* (an alphanumeric character)
测试代码:
public static void main(final String[] args) {
final Pattern p = Pattern.compile("^([a-zA-Z]+\\*?|\\*)\\w*$");
System.out.println(p.matcher("TE").matches());
System.out.println(p.matcher("*TE").matches());
System.out.println(p.matcher("TE*").matches());
System.out.println(p.matcher("T*E").matches());
System.out.println(p.matcher("*9TE").matches());
System.out.println(p.matcher("*TE*").matches());
System.out.println(p.matcher("9E").matches());
}
根据 Stargazer,如果您允许在星星之前使用字母数字,则使用以下内容:
^([a-zA-Z][a-zA-Z0-9]*\\*?|\\*)\\w*$
关于java - 我需要一个 Java 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5599567/