-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?

1

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

3 Comments

you can do it with way less code than that...
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.
the question clearly asks about getting only one value from the input. The simplest solution is always the best.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.