0

I want to read a certain part of a String in this String:

    <test>3:35</test>

The part I want to read is 3:35, but I just can't seem to figure it out. What I have currently is:

    s.skip("<test>");
    t = s.next();
    s.skip("</test>");

But of course, all I get back is 3:35</test> because I skip after t = s.next()

Can anyone explain the way too easy solution I'm probably not seeing here?

3 Answers3

0

Use Regex:

Pattern pattern = Pattern.compile("<test>(.+?)</test>");
Matcher matcher = pattern.matcher("<test>3:35</test>");
matcher.find();
System.out.println(matcher.group(1)); // Output: 3:35

P.S: Regex are not the best tool to do this kind of computation, in long term an XML parser should be used.

Sachin Gupta
  • 7,805
  • 4
  • 30
  • 45
0

If you don't want to use regex or XML parser, you can modify your solution like this -

s.skip("<test>");
    t = s.next();
   t = t.substring(0,t.indexOf("</test>"));
Sachin Aggarwal
  • 1,095
  • 8
  • 17
0

Using Regex as Sachin mentioned, or by using replaceall():

    String str = "<test>3:35</test>"; 
    str = str.replaceAll("<test>", ""); 
    str = str.replaceAll("</test>", ""); 
    System.out.println(str); 

Better to make a function which takes the original string and the strings that you want to replace as an argument, then return the desired value...

Streamsoup
  • 834
  • 8
  • 7