-3

As a response am getting following string

String response = "<span class="timeTempText">6:35a</span><span class="dividerText"> | </span><span class="timeTempText">59°F</span>"

From this i have to fetch only 6:35a and 59°F. using subString and indexOf method i can get the values from the string and but it seems like lots of code. Is there any easy way to get it.I mean using regular expression? Using regular experssion how can i get the strings.

Psl
  • 3,830
  • 16
  • 46
  • 84
  • Obligatory links: [Why you should not parse XML or HTML with a regular expression](https://stackoverflow.com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse-xml-and-html-with-a-reg), and [the unholy consequences](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454). – VGR Oct 04 '16 at 13:22

2 Answers2

2

Try this:

timeTempText">(.*?)<\/span>


import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "timeTempText\">(.*?)<\\/span>";
final String string = "<span class="timeTempText">6:35a</span><span class="dividerText"> | </span><span class="timeTempText">59°F</span>"
     + "asdfasdf asdfasdf timeTempText\">59°F</span> asdfasdf\n";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}

/* 1st Capturing Group (.?) .? matches any character (except for line terminators) *? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy)

*/

Capturing Group 1 has the value

Mustofa Rizwan
  • 10,215
  • 2
  • 28
  • 43
1

You can do it with regexes, but that's lot of code:

    String response = "<span class=\"timeTempText\">6:35a</span><span class=\"dividerText\"> | </span><span class=\"timeTempText\">59°F</span>";
    Matcher matcher = Pattern.compile("\"timeTempText\">(.*?)</span>").matcher(response);
    while (matcher.find()) {
        System.out.println(matcher.group(1));
    }

Explanation:

  • You create a Pattern
  • Then retrieve the Matcher
  • You loop through the matches with the while(matcher.find()) idiom.
  • matcher.group(1) returns the 1st group of the pattern. I.e. the matched text between the first ()

Please note that this code is very brittle. You're better off with XPATH.

Tamas Rev
  • 7,008
  • 5
  • 32
  • 49