DevX DevX - 1 month ago 6x
Java Question

how to exclude "<" in regex match

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.


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.