簡體   English   中英

如何在Java中使用正則表達式提取此字符串?

[英]How do I extract this string using a regular expression in Java?

errorString="AxisFault\n
 faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.generalException\n
 faultSubcode: \n
 faultString: My Error\n
 faultActor: \n
 faultNode: \n
 faultDetail: \n
    {}string: this is the fault detail"


Pattern pattern = Pattern.compile(".*faultString(.*)", Pattern.DOTALL);
Matcher matcher = pattern.matcher(errorString);
if (matcher.matches()) {
   String match = matcher.group(1);
   return match;
}

我想得到“我的錯誤”,但它返回到整個字符串的末尾,而不是匹配到faultString行末尾的\\ n。 我已經嘗試了許多技術讓它在生產線結束時停止,但沒有成功。

謝謝

你不應該傳遞Pattern.DOTALL ; 這會導致換行符匹配.* ,這正是你想要的。

一個更好的正則表達式是:

Pattern pattern = Pattern.compile("faultString: (.*)");

然后,使用find()來查看它是否出現在字符串中的任何位置,而不是matcher.matches()

另請注意,我已將正則表達式修改為僅對“我的錯誤”部分進行分組,而不是像您原來那樣對“我的錯誤”進行分組。

為了清楚起見,這是我測試的代碼:

Pattern pattern = Pattern.compile("faultString: (.*)");
Matcher matcher = pattern.matcher(errorString);
if (matcher.find()) {
    System.out.println(matcher.group(1));
}

其中errorString與您的相同。
輸出是:

My Error

我可能會將Chris的正則表達式清理成以下內容: ".*faultString:\\\\s*([^\\\\n]*).*"

Pattern pattern = Pattern.compile("^faultString(.*)$", Pattern.MULTILINE);

這看起來像屬性文件格式。 使用StringReader將此字符串加載到java.util.Property然后從中讀取會更容易嗎?

這適用於.matches()方法:

Pattern pattern = Pattern.compile(".*faultString([^\\n]*).*", Pattern.DOTALL);

請記住,正則表達式的東西是昂貴的。 Chetan有正確的想法。

這是一些示例代碼 -

    String errorString = "AxisFault\n"
            + "          faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.generalException\n"
            + "          faultSubcode: \n" 
            + "          faultString: My Error\n"
            + "          faultActor: \n" 
            + "          faultNode: \n"
            + "          faultDetail: \n"
            + "                 {}string: this is the fault detail";

    Properties p = new Properties();
    ByteArrayInputStream bis = new ByteArrayInputStream(errorString
            .getBytes());

    try {
        p.load(bis);
    } catch (IOException e) {

    }

    System.out.println(p.toString());
    System.out.println(p.getProperty("faultString"));

也許getFaultString :)

編輯:或((AxisFault)exception.getRootCause())。getFaultString()。 我只是覺得你可能忽略了這樣一個事實,你可以直接從AxisFault本身那里得到它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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