繁体   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