简体   繁体   English

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

[英]Need Regular Expression to retrieve Email IDs in an Exception Message between the characters < and >

Need help on Regular Expression to retrieve Email IDs in Error Stack which is like "Some Text some text line break and so on".需要有关正则表达式的帮助以在错误堆栈中检索电子邮件 ID,例如“某些文本、某些文本换行等等”。

Tried using some suggestions provided in Stack overflow.尝试使用堆栈溢出中提供的一些建议。 But most of them prints just the error但他们中的大多数只打印错误

Below are some of the options which I tried out,以下是我尝试过的一些选项,

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("<(<^>>+)>")

Actual Resulting String array contains only one value and prints the entire stack as below,实际结果字符串数组只包含一个值并打印整个堆栈如下,

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: There is no \\ in the email id. PS:电子邮件ID中没有\\。 Stack overflow did not accept the character followed by <.堆栈溢出不接受后跟 < 的字符。 So added escape character before that.所以在此之前添加了转义字符。

This should do what you want, albeit with the assumption that there will only ever be one per message.这应该做你想做的,尽管假设每条消息只会有一个。

public class someClass {
    private static final Pattern idPattern = Pattern.compile("<.*>");

    public static void main(String[] args) {
        doStuff();
    }

    public static void doStuff(){
        try{
            throwNPE();
        } catch (NullPointerException ex){
            String message = ex.getMessage();
            if(idPattern.matcher(message).matches()){
                System.out.println(getId(message));
            }
        }
    }

    public static String getId(String message){
        String[] messageParts = message.split("<|>");
        if(messageParts.length > 1){
            return messageParts[1];
        }else{
            throw new IllegalArgumentException();
        }
    }

    public static void throwNPE(){
        throw new NullPointerException("<123>");
    }
}

You only really need doStuff() and getId(String) for your example (and you can drop the static), however wanted to provide a working example.您只需要 doStuff() 和 getId(String) 作为您的示例(并且您可以删除静态),但是想提供一个工作示例。

Any explanations necessary, please ask.任何必要的解释,请询问。 Good luck!祝你好运!

这根据接受的答案正常工作, 正则表达式提取方括号之间的文本

Pattern.compile("\\<(.*?)\\>").matcher(e.getMessage());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM