gpt4 book ai didi

[j-*] 的 Java 模式

转载 作者:行者123 更新时间:2023-11-29 07:53:46 24 4
gpt4 key购买 nike

请帮我进行模式匹配。我想构建一个模式,它将匹配以下字符串中以 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com