Java 具有多种可能结尾的正则表达式

Java regex with multiple possible endings

我需要编写一个正则表达式来匹配具有 txt、htm 或 html 扩展名的文件名。我知道 parens 将字符组合在一起并且括号允许匹配一组中的一个字符,所以我尝试组合这些方法,但它不起作用。要测试的字符串在parts[1]中。 .* 应该匹配任意数量的字符,然后是 \\。将是点,然后我尝试组合方括号和圆括号。

if (!Pattern.matches(".*\.[(txt)(htm)(html)]", parts[1])) {
    System.err.println("501 Not Implemented: " + parts[1] + "\n");
}

只需尝试使用以下正则表达式:

".*\.(txt|html?)$"

应该是:

if (!Pattern.matches(".*?\.(txt|html?)", parts[1])) {
    System.err.println("501 Not Implemented: " + parts[1] + "\n");
}
  • 字符内没有文本分组 class [...]
  • matches 方法采用锚点,因此不需要 ^$