Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Regex从响应数据中提取特定字符串_Java_Regex - Fatal编程技术网

Java Regex从响应数据中提取特定字符串

Java Regex从响应数据中提取特定字符串,java,regex,Java,Regex,作为响应,我得到以下字符串 String response = "<span class="timeTempText">6:35a</span><span class="dividerText"> | </span><span class="timeTempText">59°F</span>" String response=“6:35a | 59华氏度” 从这里,我只能获取6:35a和59°F. 使用subStrin

作为响应,我得到以下字符串

String response = "<span class="timeTempText">6:35a</span><span class="dividerText"> | </span><span class="timeTempText">59°F</span>"
String response=“6:35a | 59华氏度”
从这里,我只能获取
6:35a和59°F.
使用
subString
indexOf
方法,我可以从字符串中获取值,但它似乎有很多代码。 有什么简单的方法可以得到它吗?我的意思是使用正则表达式? 使用常规Expression如何获取字符串。

尝试以下方法:

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));
    }
}
timetestext”>(*
导入java.util.regex.Matcher;
导入java.util.regex.Pattern;
最后一个字符串regex=“timetestext\”>(.*);
最终字符串字符串=“6:35a | 59°F”
+“asdfasdf asdfasdf TIMETERTEXT\”>59华氏度asdfasdf\n”;
最终模式=Pattern.compile(regex);
final Matcher Matcher=pattern.Matcher(字符串);
while(matcher.find()){
System.out.println(“完全匹配:+matcher.group(0));

对于(inti=1;i您可以使用正则表达式来实现,但这需要大量代码:

    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));
    }
String response=“6:35a | 59°F”;
Matcher Matcher=Pattern.compile(“\”timetestext\“>(.*?)).Matcher(响应);
while(matcher.find()){
系统输出println(匹配器组(1));
}
说明:

  • 您创建了一个
    模式
  • 然后检索匹配器
  • 使用
    while(matcher.find())
    习惯用法循环匹配
  • matcher.group(1)
    返回模式的第一组,即第一组
    ()
  • 请注意,此代码非常脆弱。您最好使用XPATH。

    Pattern r=Pattern.compile(timetestext“>(.*));强制性链接:,和。