首页 > 解决方案 > 电子邮件的正则表达式,其间应包含连字符,但不能在开始和结束位置

问题描述

我有一个满足条件的正则表达式,但它允许在开头使用连字符。一开始怎么限制。我想要在开头限制连字符的相同正则表达式,因为它允许我需要的其他一些字符。

/^[A-Z0-9-._%+]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;

提前致谢

标签: javaregex

解决方案


这似乎对我有用

public class QuickyTest{

   static String[] testVectors = { "alaskjf", 
                          "o-kay@example.com",
                                 "-dash@x.AA", 
                                 "dash-@y.ZZ" };

   public static void main( String[] args ) {
      Pattern pattern = Pattern.compile( "(?i:[A-Z0-9._%+]+|[A-Z0-9._%+]+[A-Z0-9._%+-]+[A-Z0-9._%+]+@([A-Z0-9-]+.)+[A-Z]{2,4})" );
      for( String test : testVectors ) {
         Matcher match = pattern.matcher( test );
         System.out.println( test + " : " + match.matches() );
      }
   }

}

推荐阅读