I have to parse a String in 3 stages. Only first stage works, in 2 and 3 stage matcher.groupCount() returns 0 - which means it found nothing. I was testing my regex in online tester and it was just fine. But here it doesn't work. So the question is maybe I miss something or regex has mistake in it?
String rawText = "ashjdajsdg:[requiredPartForFirstPattern]}asdassdasd";
Pattern firstPattern = Pattern.compile("(:\\[)(.*?)(\\]})");
List<String> firstList = parseContent(rawText, firstPattern);
After execution firstList should contain only one value (in this case): "requiredPartForFirstPattern" (could be any char or any char sequence).
Now I am iterating all the values in the firstList and checking them with 2 pattern:
All values in firstList will have such form: "[someText1],[someText2],[someText3]".
String rawText = "[someText1],[someText2],[someText3]";
Pattern secondPattern = Pattern.compile("(\\[([^]]*)\\])");
List<String> secondList = parseContent(rawText, secondPattern);
After execution secondList should contain this values (in this case): "someText1","someText2","someText3".
And finally the third stage. I iterate all values in secondList and check them with 3 pattern. All values in secondList will have such form: "'someValue1','someValue2'".
String rawText = "'someValue1','someValue2'";
Pattern thirdPattern = Pattern.compile("('(.*?)')");
List<String> thirdList = parseContent(rawText, secondPattern);
After execution secondList should contain this values (in this case): "someValue1","someValue2".
My parseContent method:
private List<String> parseContent(String content, Pattern pattern) {
List<String> matchedList = new LinkedList<>();
Matcher matcher = pattern.matcher(content);
if (matcher.find()) {
for(int matchIndex = 0; matchIndex < matcher.groupCount(); ++matchIndex) {
matchedList.add(matcher.group(matchIndex));
}
}
return matchedList;
}
You should have while (matcher.find()) instead of an if-statement.
if (matcher.find()) {
for(int matchIndex = 0; matchIndex < matcher.groupCount(); ++matchIndex) {
matchedList.add(matcher.group(matchIndex));
}
}
I've replaced above code with this one:
while (matcher.find()) {
matchedList.add(matcher.group(1));
}
Works fine, ty for help.