0

I have a regular expression which is satisfying the condition but it is allowing hyphen at the beginning. How to restrict at the beginning. I want the same regular expression with restriction of hyphen at the beginning as it is allowing some other characters which I required.

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

Thanks in advance

mle
  • 2,466
  • 1
  • 19
  • 25
  • Something like `[A-Z]+|[A-Z]+[A-Z-]+[A-Z]+` I think, where A-Z is whatever character set you want to allow. Just require at least one non- dash character at the beginning and end of what your current expression is. – markspace Apr 03 '19 at 16:04
  • email validation is not so simple. On the other hand, it is a well-known issue. Check this one https://stackoverflow.com/questions/201323/how-to-validate-an-email-address-using-a-regular-expression – Dr Phil Apr 03 '19 at 16:16
  • Email validation via regex is impossible I think, but his narrow question - "How do I exclude a dash at the beginning or end" is pretty well scoped. @DrPhil – markspace Apr 03 '19 at 16:19

1 Answers1

0

This seems to work for me

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() );
      }
   }

}
markspace
  • 10,621
  • 3
  • 25
  • 39