0

I have a String which looks like "<name><address> and <Phone_1>". I have get to get the result like

1) <name>
2) <address>
3) <Phone_1>

I have tried using regex "<(.*)>" but it returns just one result.

Andy Ray
  • 28,150
  • 13
  • 92
  • 132
DevX
  • 450
  • 4
  • 18

3 Answers3

1

The regex you want is

<([^<>]+?)><([^<>]+?)> and <([^<>]+?)>

Which will then spit out the stuff you want in the 3 capture groups. The full code would then look something like this:

Matcher m = Pattern.compile("<([^<>]+?)><([^<>]+?)> and <([^<>]+?)>").matcher(string);

if (m.find()) {
    String name = m.group(1);
    String address = m.group(2);
    String phone = m.group(3);
}
Sebastian Lenartowicz
  • 4,549
  • 4
  • 28
  • 38
1

The pattern .* in a regex is greedy. It will match as many characters as possible between the first < it finds and the last possible > it can find. In the case of your string it finds the first <, then looks for as much text as possible until a >, which it will find at the very end of the string.

You want a non-greedy or "lazy" pattern, which will match as few characters as possible. Simply <(.+?)>. The question mark is the syntax for non-greedy. See also this question.

Community
  • 1
  • 1
Andy Ray
  • 28,150
  • 13
  • 92
  • 132
1

This will work if you have dynamic number of groups.

Pattern p = Pattern.compile("(<\\w+>)");
Matcher m = p.matcher("<name><address> and <Phone_1>");
while (m.find()) {
    System.out.println(m.group());
}
DeepakV
  • 2,340
  • 1
  • 16
  • 20