aherlambang
aherlambang

Reputation: 14418

String parsing in java

If I have a long string, say:

"blah blah blah blah blah .............. <ns:return>72.5</ns:return>......abcdejijalskjd;a;l&*^@#()&...."

and I want to extract the value in between the tag, how can I do that?

Upvotes: 0

Views: 160

Answers (5)

Thilo
Thilo

Reputation: 262842

Use Commons Lang StringUtils

String between = substringBetween(longString, "<ns:return>", "</ns:return>");

Upvotes: 0

Cody Butz
Cody Butz

Reputation: 294

Do something like:

String str = "blah .... <ns:return>72.5</ns:return>";
String searchBegin = "<ns:return>";
String searchEnd = "</ns:return>";
String subStr = str.substring(str.indexOf(searchBegin) + searchBegin.length(), str.indexOf(searchEnd));

Upvotes: 3

masher
masher

Reputation: 4116

If everything is always going to be the same, you could use a regex...

(?<=<ns:return>)([0-9.]+)(?=</ns:return>)

Upvotes: 1

Jack
Jack

Reputation: 133669

You can use regular expressions, something like:

Pattern p = Pattern.compile(".*<ns:return>(.*)</ns:return>.*");
Matcher m = p.matcher(yourString);

float yourValue = Float.parseFloat(m.group(1));

Upvotes: 0

gigadot
gigadot

Reputation: 8969

If it's an xml then use xml parser. Otherwise, you can use regular expression.

Upvotes: 5

Related Questions