-1

I have a string like this:

"text1 <text2> text3"

I want to grab only the text in <>. So I need to get text2. How can I do it?

Finkelson
  • 2,921
  • 4
  • 31
  • 49
  • Mandatory link: [RegEx match open tags except XHTML self-contained tags](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – Pshemo May 06 '16 at 12:14

2 Answers2

1

You can do it like this:

String value = "text1 <text2> text3 <text4>";
Pattern pattern = Pattern.compile("<([^>]*)>");
Matcher matcher = pattern.matcher(value);
while (matcher.find()) {
    System.out.println(matcher.group(1));
}

Output:

text2
text4

Response Update:

Assuming that you know that you have only one value to extract, Bohemian proposes a simpler approach, he proposes to proceed as next:

String value = "text1 <text2> text3";
String target = value.replaceAll(".*<(.*)>.*", "$1");
System.out.println(target);

Output:

text2
Community
  • 1
  • 1
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
  • you can do it with way less code than that... – Bohemian May 06 '16 at 12:10
  • It's not even a line, it needs just a method call: `String target = value.replaceAll(".*<(.*)>.*", "$1");`. Less code == less bugs, easier to read and maintain. – Bohemian May 06 '16 at 13:58
  • the question clearly asks about getting only one value from the input. The simplest solution is always the best. – Bohemian May 06 '16 at 14:57
0

I suggest you to split this string using " " as a separator - you will get 3 -elements array and the second one is what you are looking for

dacio
  • 51
  • 8