0

I'm trying regex after a long time. I'm not sure if the issue is with regex or the logic.

String test = "project/components/content;contentLabel|contentDec"; String regex = "(([A-Za-z0-9-/]*);([A-Za-z0-9]*))"; Map<Integer, String> matchingGroups = new HashMap<>(); Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(test); //System.out.println("Input: " + test + "\n"); //System.out.println("Regex: " + regex + "\n"); //System.out.println("Matcher Count: " + matcher.groupCount() + "\n"); if (matcher != null && matcher.find()) { for (int i = 0; i < matcher.groupCount(); i++) { System.out.println(i + " -> " + matcher.group(i) + "\n"); } } 

I was expecting the above to give me the output as below:

0 -> project/components/content;contentLabel|contentDec 1 -> project/components/content 2 -> contentLabel|contentDec 

But when running the code the group extractions are off.

Any help would be really appreciated.

Thanks!

2
  • On executing this, I'm still unable to get the last group information. This is the output I see now -------->> 0 -> project/components/content;contentLabel|contentDec 1 -> project/components/content Commented Mar 27, 2020 at 2:28
  • @Sal no need to escape / Commented Mar 27, 2020 at 2:45

1 Answer 1

1

You have a few issues:

  1. You're missing | in your second character class.
  2. You have an unnecessary capture group around the whole regex.
  3. When outputting the groups, you need to use <= matcher.groupCount() because matcher.group(0) is reserved for the whole match, so your capture groups are in group(1) and group(2).

This will work:

String test = "project/components/content;contentLabel|contentDec"; String regex = "([A-Za-z0-9-/]*);([A-Za-z0-9|]*)"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(test); if (matcher != null && matcher.find()) { for (int i = 0; i <= matcher.groupCount(); i++) { System.out.println(i + " -> " + matcher.group(i) + "\n"); } } 
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! This worked. Great explanation, especially the 3rd point. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.