我正在使用正则表达式从网页中提取黄金报价。我正在将其解析为字符串,然后使用正则表达式来提取引号。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HelloWorld{
public static void main(String []args){
String str = "----------------------------------------------------------------------"
+ "Metals Bid Ask Change Low High "
+ "----------------------------------------------------------------------"
+ "Gold 1176.40 1177.40 -8.60 -0.73% 1171.90 1183.90";
Pattern pattern = Pattern.compile("Gold(\\s{9})(\\d{4}).(\\d{2})");
Matcher matcher = pattern.matcher(str);
if (matcher.find())
{
System.out.println(matcher.group());
}
else {
System.out.println("No string found");
}
}
}
此代码找到我想要的“Gold 1176.40”字符串,但我无法将其保存为另一个字符串,如
String temp = matcher.group();
我该怎么做?
答案 0 :(得分:1)
在if条件之前声明一个临时变量,然后将匹配的字符串附加到该temp
变量。
String temp = "";
Pattern pattern = Pattern.compile("Gold(\\s{9})(\\d{4})\\.(\\d{2})");
Matcher matcher = pattern.matcher(str);
if (matcher.find())
{
temp = temp + matcher.group();
}
else {
System.out.println("No string found");
}
答案 1 :(得分:0)
如果您感兴趣,可以单行进行。
String str = "----------------------------------------------------------------------"
+ "Metals Bid Ask Change Low High "
+ "----------------------------------------------------------------------"
+ "Gold 1176.40 1177.40 -8.60 -0.73% 1171.90 1183.90";
String s = str.substring(str.indexOf("Gold"))).replaceAll("(Gold\\s{9}\\d{4}.\\d{2}).*", "$1");