0

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?

4
  • What is the "tag" you're referring to? And what's the value in your example? Commented Dec 2, 2010 at 2:29
  • What do you mean by "in between the tag"? Commented Dec 2, 2010 at 2:29
  • sorry, it's missing if I didn't put it as code Commented Dec 2, 2010 at 2:30
  • If it's XML, you might want to explore the use of DOM or SAX XML parsing. onjava.com/pub/a/onjava/2002/06/26/xml.html Might be too heavy weight for your app, though. Commented Dec 2, 2010 at 2:34

5 Answers 5

5

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

Sign up to request clarification or add additional context in comments.

Comments

3

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));

1 Comment

+1, for keeping it simple. Why use the overhead of a regex for something this simple. The indexOf search will be faster and use less resources and its easier for anybody to understand what is going on. So far each regex solution uses a different regex, proving how complex even a simple regex can be. The only suggestion is to do the search in two steps. Find the location of the start tag first and then search for the end tag from that location so you don't search the string twice.
1

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

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

Comments

0

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));

Comments

0

Use Commons Lang StringUtils

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.