简体   繁体   English

Java模式匹配:Pattern.compile

[英]Java Pattern Matching: Pattern.compile

I have an edit box. 我有一个编辑框。 I am checking if the email address entered is valid or not. 我正在检查输入的电子邮件地址是否有效。

Pattern pattern1 = Pattern.compile("^[\\w-]*@[\\.\\w-]*$");
Pattern pattern2 = Pattern.compile("^\\w+$");
Matcher matcher1 = pattern1.matcher(string);
Matcher matcher2 = pattern2.matcher(string);    
return matcher1.matches();
return matcher2.matches();

Problem with this if my input my email address as spunker.baba@foo.com. 如果我输入我的电子邮件地址为spunker.baba@foo.com,则会出现此问题。 matcher return false. 匹配器返回false。 It consider the char "." 它考虑字符“。” as invalid. 视为无效。

How should i modify my code such that it supports "." 我应该如何修改我的代码以使其支持“。” and matcher return true. 匹配器返回true。

It's not clear why you've got two patterns (and two return statements!) instead of one... but your first pattern only includes \\w and - before the @ sign, although it allows . 尚不清楚为什么有两个模式(和两个return语句!)而不是一个...。但是您的第一个模式仅在\\w符号之前包含\\w- ,尽管它允许. afterwards. 然后。 That's easy to modify, so that the first part is the same as the second part: 这很容易修改,因此第一部分与第二部分相同:

Pattern pattern1 = Pattern.compile("^[\\.\\w-]*@[\\.\\w-]*$");

However, there are plenty of sites giving rather more exact email address matching regular expression patterns - for example this one in Perl (which I suspect will port simply enough to Java). 但是,有很多站点提供了与正则表达式模式相匹配的更为准确的电子邮件地址-例如,Perl中的这一地址(我怀疑可以将其简单地移植到Java中)。 There's also a page with a fairly long explanation and Java code , if you want to also cope with addresses including friendly names. 如果您还想处理包括友好名称的地址,那么还会有一个页面,其中包含相当长的说明和Java代码 I'm sure if you search around you'll find a pattern which meets your exact needs - although quite how you judge which pages are reliable is another matter. 我敢肯定,如果您四处搜寻,就会找到符合您确切需求的模式-尽管完全如何判断哪些页面是可靠的是另一回事。

EDIT: If you want to be able to match without the last part, you can make it optional like this: 编辑:如果您希望不使用最后一部分就能进行匹配,可以将其设置为可选,如下所示:

Pattern pattern1 = Pattern.compile("^[\\.\\w-]*(@[\\.\\w-]*)?$");
Pattern.compile("^[\\w-\.]*@[\\.\\w-]*$")

Note that this pattern will match non valid strings (assuming @ isn't a valid email address). 请注意,此模式将匹配无效的字符串(假设@不是有效的电子邮件地址)。 And it will also not match other valid email addresses (ie name+other@gmail.com ) 而且它也将不匹配其他有效的电子邮件地址(即name+other@gmail.com

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

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