简体   繁体   English

正则表达式从响应数据中提取特定字符串

[英]Regex to extrat particular strings from a response data

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.从这里我只需要获取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.使用subStringindexOf方法我可以从字符串中获取值,但它似乎有很多代码。 Is there any easy way to get it.I mean using regular expression?有什么简单的方法可以得到它。我的意思是使用正则表达式? Using regular experssion how can i get the strings.使用常规表达式如何获取字符串。

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捕获组 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你创建一个Pattern
  • Then retrieve the Matcher然后检索Matcher
  • You loop through the matches with the while(matcher.find()) idiom.您使用while(matcher.find())习语遍历匹配项。
  • matcher.group(1) returns the 1st group of the pattern. matcher.group(1)返回模式的第一组。 Ie the matched text between the first ()即第一个()之间的匹配文本

Please note that this code is very brittle.请注意,此代码非常脆弱。 You're better off with XPATH.最好使用 XPATH。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM