簡體   English   中英

在Java中使用正則表達式提取子字符串

[英]Using regex in Java to extract a substring

我正在使用正則表達式從網頁中提取黃金報價。 我將其解析為字符串,然后使用正則表達式提取引號。

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();

我怎樣才能做到這一點?

在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");
}

如果您有興趣,請單行執行。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM