需要正则表达式来检索异常消息中字符<和>之间的电子邮件 ID

需要有关正则表达式的帮助以在错误堆栈中检索电子邮件ID,例如“某些文本,某些文本换行符等”。


已尝试使用堆栈溢出中提供的一些建议。但是他们中的大多数只打印错误


以下是我尝试过的一些选项,


Matcher m = Pattern.compile("\\<([^>]+)\\)").matcher(e.getMessage());

while(m.find())

{

    System.out.println(m.group(1));

}

System.out.println(e.getMessage().split("<(<^>>+)>"));


exception.getMessage().split("\\[([^]]+)\\]")

exception.getMessage().split("\\<\"(.*?)\"\\>")

exception.getMessage().split("<(<^>>+)>")

实际结果字符串数组仅包含一个值,并按如下方式打印整个堆栈,


Failed messages: javax.mail.SendFailedException: Invalid Addresses;

  nested exception is:

    com.sun.mail.smtp.SMTPAddressFailedException: 550 5.0.0 <abc@def.com>... User unknown

;

  nested exception is:

    com.sun.mail.smtp.SMTPAddressFailedException: 550 5.0.0 <def@ghi.com>... User unknown

;

PS:电子邮件 ID 中没有 \。堆栈溢出不接受后跟<的字符。所以在此之前添加了转义字符。


慕盖茨4494581
浏览 134回答 2
2回答

qq_遁去的一_1

根据正则表达式中接受的答案,这可以正常工作,以提取方括号之间的文本Pattern.compile("\\<(.*?)\\>").matcher(e.getMessage());

吃鸡游戏

这应该做你想要的,尽管假设每条消息只有一个。public class someClass {&nbsp; &nbsp; private static final Pattern idPattern = Pattern.compile("<.*>");&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; doStuff();&nbsp; &nbsp; }&nbsp; &nbsp; public static void doStuff(){&nbsp; &nbsp; &nbsp; &nbsp; try{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throwNPE();&nbsp; &nbsp; &nbsp; &nbsp; } catch (NullPointerException ex){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String message = ex.getMessage();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(idPattern.matcher(message).matches()){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(getId(message));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public static String getId(String message){&nbsp; &nbsp; &nbsp; &nbsp; String[] messageParts = message.split("<|>");&nbsp; &nbsp; &nbsp; &nbsp; if(messageParts.length > 1){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return messageParts[1];&nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new IllegalArgumentException();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public static void throwNPE(){&nbsp; &nbsp; &nbsp; &nbsp; throw new NullPointerException("<123>");&nbsp; &nbsp; }}你只需要 doStuff() 和 getId(字符串) 作为你的示例(你可以删除静态),但是想要提供一个工作示例。任何必要的解释,请询问。祝你好运!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java