[英]Using regex in Java to extract a substring
I am using a regex to extract the gold quotes from a webpage. 我正在使用正则表达式从网页中提取黄金报价。 I am parsing it to a string, then using regex to extract the quotes.
我将其解析为字符串,然后使用正则表达式提取引号。
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");
}
}
}
This code finds the "Gold 1176.40" string that I want, but I can't save it as another string, as in 这段代码找到了我想要的“ Gold 1176.40”字符串,但是我无法将其另存为另一个字符串,例如
String temp = matcher.group();
How can I do this? 我怎样才能做到这一点?
Declare a temp variable before the if condition and then append the matched string to that temp
variable. 在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");
}
If you are interest do it in single line. 如果您有兴趣,请单行执行。
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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.