0

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")

However the matches() is not even returning true. Why do these strings not match that pattern, what is wrong with the pattern?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
user3237736
  • 845
  • 1
  • 9
  • 24

3 Answers3

2

When using a formal pattern matcher in Java, we don't need to use a pattern which matches the entire input. Instead, just use the pattern \[ISOLATION GROUP ([^\]]+) to get all matches:

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

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Thanks. it turns out my real problem was that I didn't know you have to use m.find() here. I had just if(m.matches()) but that was always false (and is false for your example too). It's not really clear to me from the documentation of these methods why I would have to do that.. – user3237736 Apr 07 '18 at 15:57
  • 1
    Your original pattern is wrong, and wouldn't work in either case. I think matches insists on matching the entire input, which isn't really what we want here. We want to iterate over the entire text and just find what we are looking for. – Tim Biegeleisen Apr 07 '18 at 16:00
0

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)[^\\]]+
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
-2

This should work

Pattern.compile(".*?\\[ISOLATION GROUP .*\\].*");
nitnamby
  • 404
  • 2
  • 8