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
  • 30,372
  • 14
  • 101
  • 138
DevX
  • 490
  • 6
  • 23

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,695
  • 4
  • 28
  • 39
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
  • 30,372
  • 14
  • 101
  • 138
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,420
  • 1
  • 16
  • 20