Java - Reg expression using groups

From the line I need to pull out the groups that match the given pattern.

Example string: <XmlLrvs>FIRST</XmlLrvs><XmlLrvs>SECOND</XmlLrvs><XmlLrvs>Third</XmlLrvs>

Each group starts with <XmlLrvs> and ends with </XmlLrvs> . Here is a snippet of my code ...

 String patternStr = "(<XmlLrvs>.+?</XmlLrvs>)+"; // Compile and use regular expression Pattern pattern = Pattern.compile(patternStr); Matcher matcher = pattern.matcher(text); matcher.matches(); // Get all groups for this match for (int i = 1; i<=matcher.groupCount(); i++) { System.out.println(matcher.group(i)); } 

The output is <XmlLrvs>Third</XmlLrvs> . I expect the group to be first and second, but they will not be captured. Can anyone help?

+4
source share
2 answers

You iterate over groups when you need to iterate over matches. The matches() method checks all input for compliance. You want to use the find() method.

Edit

 matcher.matches(); for (int i = 1; i<=matcher.groupCount(); i++) { System.out.println(matcher.group(i)); } 

to

 while (matcher.find()) { System.out.println(matcher.group(1)); } 
+8
source

Try String patternStr = "<XmlLrvs>(.*?)</XmlLrvs>";
String text = "<XmlLrvs>FIRST</XmlLrvs><XmlLrvs>SECOND</XmlLrvs><XmlLrvs>Third</XmlLrvs>";
Pattern pattern = Pattern.compile(patternStr);
String patternStr = "<XmlLrvs>(.*?)</XmlLrvs>";
String text = "<XmlLrvs>FIRST</XmlLrvs><XmlLrvs>SECOND</XmlLrvs><XmlLrvs>Third</XmlLrvs>";
Pattern pattern = Pattern.compile(patternStr);

Matcher matcher = pattern.matcher (text);

while (matcher.find ()) {
System.out.println (matcher.group (1));
}

The output is FIRST, SECOND, Third

0
source

Source: https://habr.com/ru/post/1286779/


All Articles