简体   繁体   English

我的RegEx模式出了什么问题

[英]What's wrong with my RegEx pattern

I have this pattern: 我有这种模式:

Pattern.compile(".*?\\[ISOLATION GROUP (^]+)].*");

I assumed this would match, for example, these two strings: 我假设这将与以下两个字符串匹配:

"[ISOLATION GROUP X] blabla"
"[OTHER FLAG][ISOLATION GROUP Y] blabla"

and then with group(1) I could get the name of the isolation group (in the above examples, "X" resp. "Y") 然后使用group(1)可以获得隔离组的名称(在上面的示例中,“ X”代表“ Y”)

However the matches() is not even returning true. 但是matches()甚至没有返回true。 Why do these strings not match that pattern, what is wrong with the pattern? 为什么这些字符串与该模式不匹配,该模式出了什么问题?

When using a formal pattern matcher in Java, we don't need to use a pattern which matches the entire input. 在Java中使用正式的模式匹配器时,我们不需要使用与整个输入匹配的模式。 Instead, just use the pattern \\[ISOLATION GROUP ([^\\]]+) to get all matches: 相反,只需使用模式\\[ISOLATION GROUP ([^\\]]+)即可获得所有匹配项:

String input = "[ISOLATION GROUP X] blabla";
input += "[OTHER FLAG][ISOLATION GROUP Y] blabla";
String pattern = "\\[ISOLATION GROUP ([^\\]]+)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
while (m.find()) {
    System.out.println("Found value: " + m.group(1));
}

Found value: X
Found value: Y

Demo 演示版

You forgot to enclose the characters of the group within braces. 您忘记将组的字符括在大括号中。

.*?\\[ISOLATION GROUP (^]+)].*

should become 应该成为

.*?\\[ISOLATION GROUP ([^\\]]+)\\].*

Demo 演示版


Positive lookbehind 正向后看

Try using a positive lookbehind maybe? 尝试使用正向后视吗? it is much more easier than your solution I think and you just have to deal with a single group 它比您认为的解决方案容易得多,您只需要处理一个小组

(?<=ISOLATION GROUP\s)[^\\]]+

这应该工作

Pattern.compile(".*?\\[ISOLATION GROUP .*\\].*");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM