[j-*] 的 Java 模式

标签 java regex

请帮我进行模式匹配。我想构建一个模式,它将匹配以下字符串中以 j-c- 开头的单词(例如)

[j-test] is a [c-test]'s name with [foo] and [bar]

该模式需要找到 [j-test][c-test](包括括号)。

到目前为止我尝试了什么?

String template = "[j-test] is a [c-test]'s name with [foo] and [bar]";
Pattern patt = Pattern.compile("\\[[*[j|c]\\-\\w\\-\\+\\d]+\\]");
Matcher m = patt.matcher(template);
while (m.find()) {
    System.out.println(m.group());
}

它给出的输出如下

[j-test]
[c-test]
[foo]
[bar]

这是错误的。请帮助我,感谢您抽出时间参与此话题。

最佳答案

在字符类中,您不需要使用交替来匹配jc。字符类本身意味着匹配其中的任何单个字符。因此,[jc] 本身将匹配 jc

此外,您不需要匹配 j-c- 之后的模式,因为您不必担心它们,只要它们开始使用 j-c-

简单地使用这个模式:

Pattern patt = Pattern.compile("\\[[jc]-[^\\]]*\\]");

解释:

Pattern patt = Pattern.compile("(?x)      "   // Embedded flag for Pattern.COMMENT
                             + "\\[       "   // Match starting `[`
                             + "    [jc]  "     // Match j or c
                             + "    -     "     // then a hyphen
                             + "    [^    "     // A negated character class
                             + "       \\]"        // Match any character except ] 
                             + "    ]*    "     // 0 or more times
                             + "\\]       "); // till the closing ]

在正则表达式中使用 (?x) 标志,忽略空格。编写可读的正则表达式通常很有帮助。

关于[j-*] 的 Java 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19357129/

相关文章:

javascript - jQuery 中的正则表达式困惑 (1.5.2)

c++ - 这个正则表达式 "mismatched"的括号是什么?

用于递归查找字符串的正则表达式?

java - 不同(不相同)的副本集是从单例对象返回的

java - 尝试将 List<String> 转换为 List<Integer> 时出错

Java RMI : how InitialContext. Lookup() 有效

java - Spring Data MongoDB 如何从系统属性设置索引 ttl

python - 第一场比赛后停止

java - 正则表达式查找最后一个下划线后给定数量的字符

java - 安卓 ListView : how to change background color of specific cells (by index)?