Maurizio Sorrentino
Maurizio Sorrentino

Reputation: 1

Regex multiple matches concatenated

I have a string like this "@@VV 1 ?? 28 > ##@@VV 3 78 ?? > ##@@VV ?? 5 27 > ##" and I wants extract with a regex the three groups identifyed by this pattern "@@VV .>.##". But if I compile my test string with previous pattern syntax I extract whole test string as a group and not three groups. How can I define the regex string and get three groups?

public static void main(String[] args) {
  String INPUT = "@@VV 1 ?? 28 > ##@@VV 3 78 ?? > ##@@VV ?? 5 27 > ##";
  String startChars = "@@";
  String sepChars = ">";
  String endChars = "##";
  String REGEX = startChars+"VV .*"+sepChars+".*"+endChars;
  Pattern pattern = Pattern.compile(REGEX, Pattern.MULTILINE | Pattern.DOTALL);

  // get a matcher object
  Matcher matcher = pattern.matcher(INPUT);
 //Prints the number of capturing groups in this matcher's pattern. 
  System.out.println("Group Count: "+matcher.groupCount());
  while(matcher.find()) {

     System.out.println(matcher.group());
  }      
}

Expected results:
Group Count: 3
@@VV 1 ?? 28 > ##
@@VV 3 78 ?? > ##
@@VV ?? 5 27 > ##

Actual results:
Group Count: 0
@@VV 1 ?? 28 > ##@@VV 3 78 ?? > ##@@VV ?? 5 27 > ##

Upvotes: 0

Views: 37

Answers (2)

Sal
Sal

Reputation: 1317

Your are missing the capturing group: Enclosed by parenthesis.

The regex: (@@VV.*?> ##)

Upvotes: 0

Antoniossss
Antoniossss

Reputation: 32517

Try to use "lazy" operators

startChars+"VV .*?"+sepChars+".*?"+endChars

notice .*?

Here is working example. https://www.regextester.com/?fam=108741

Upvotes: 2

Related Questions