java - 我需要一个 Java 正则表达式

标签 java regex

我目前正在使用以下正则表达式:

^[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/

相关文章:

java - 为什么arraylist的新容量是(oldCapacity * 3)/2 + 1?

java - UCanAccess 初始化程序错误(在没有 IDE 的情况下编译/运行)

javascript - 使用正则表达式和 javascript 每 2 个单词插入回车符

c - 适用于 Windows 的 Regex.h

javascript - 无法理解为什么 Javascript 正则表达式不起作用

java - H2 - 在 Java 中构建并执行查询以进行日期比较

java - 如何使 Java URI 类停止使用文件

java - Jackson序列化忽略迭代器类的 '@JsonTypeInfo'和 '@JsonIgnore'?

javascript - 尝试匹配 JavaScript 字符串上的所有正则表达式

java - 使用正则表达式屏蔽字符串的一部分