简体   繁体   English

正则表达式在完整的 XML 字符串或普通字符串中抓取验证 email 地址

[英]Regex to grab validate email address in complete XML string or normal string

Need to grab string text of email value in big XML/normal string.需要在大 XML/普通字符串中抓取 email 值的字符串文本。

Been working with Regex for it and as of now below Regex is working correctly for normal String Regex: ^[\\w;#$%&amp?'*+/=?`{|}~^-]+(:.\\;[\\w?#$%&amp?'*+/=:`{|}~^-]+)*@(.,[a-zA-Z0-9-]+\\.)+[a-zA-Z]{1,6}$一直在使用正则表达式,截至目前,正则表达式对于普通字符串正则表达式正常工作: ^[\\w;#$%&amp?'*+/=?`{|}~^-]+(:.\\;[\\w?#$%&amp?'*+/=:`{|}~^-]+)*@(.,[a-zA-Z0-9-]+\\.)+[a-zA-Z]{1,6}$

Text: paris@france.c文本: paris@france.c

but in case when above text is enclosed in XML tag it fails to return.但如果上面的文本包含在 XML 标签中,则无法返回。 <email>paris@france.c</email>

I am trying to amend some change to this regex so that it will work for both of the scenarios我正在尝试修改此正则表达式的一些更改,以便它适用于这两种情况

You have put ^ at the beginning which means the "Start of the string", and $ at the end which means the "End of the string".您已将^放在开头,表示“字符串的开头”,将$放在结尾,表示“字符串的结尾”。 Now, look at your string:现在,看看你的字符串:

<email>paris@france.c</email>

Do you think, it starts and ends with an email address?你认为它以 email 地址开头和结尾吗?

I have removed them and also escaped the - in your regex.我已经删除了它们并在你的正则表达式中转义了- Here you can check the following auto-generated Java code with the updated regex.在这里,您可以使用更新的正则表达式检查以下自动生成的 Java 代码。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Example {
    public static void main(String[] args) {
        final String regex = "[\\w!#$%&amp;'*+/=?`\\{|\\}~^\\-]+(?:\\\\.[\\w!#$%&amp;'*+/=?`\\{|\\}~^\\-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{1,6}";
        final String string = "paris@france.c\n"
     + "<email>paris@france.c</email>";
        
        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        final Matcher matcher = pattern.matcher(string);
        
        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));
            
            for (int i = 1; i <= matcher.groupCount(); i++) {
                System.out.println("Group " + i + ": " + matcher.group(i));
            }
        }
    }
}

Output : Output :

Full match: paris@france.c
Full match: paris@france.c

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

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