Anil
Anil

Reputation: 2455

How to extract a part of string

My java program generates a set of lines as output like

Give input: 4+5
4+5 = <<9>>

The answer is displayed between << >>. I just want to extract the answer 9. How can i do that? Should i use pattern matching?

Upvotes: 0

Views: 279

Answers (3)

Sid Malani
Sid Malani

Reputation: 2116

String str = "<<9>>";

String prefix = "<<";
String postfix = ">>";

String answer = str.substring(prefix.length, str.indexOf(postfix));

Upvotes: 2

Nick Rolando
Nick Rolando

Reputation: 26167

Here is some regex to help

    String answer = "<<9>>";
    Pattern pat = Pattern.compile("\\d+");
    Matcher mat = pat.matcher(answer);
    mat.find();
    answer = mat.group();
    System.out.println(answer);

If the string will always be in this format <<n>>, then @Sid solution is better as regex isn't needed.

Upvotes: 3

Emmanuel Sys
Emmanuel Sys

Reputation: 815

Use some regular expression : http://java.sun.com/developer/technicalArticles/releases/1.4regex/

Or do it by hand using indexOf.

Upvotes: 2

Related Questions