简体   繁体   中英

Validating Email address using regex

I have been using this regex to validate email addresses. Files found not to have valid Email addresses on a certain line are deleted:

 FileInputStream fsdel = new FileInputStream("C:/Folder/" + filefinal[o]);
                BufferedReader brdel = new BufferedReader(new InputStreamReader(fsdel));
                for (int j = 0; j < 4; j++) {
                    brdel.readLine();
                }
                String email = brdel.readLine();
                String mine = email.trim();
                String lineIwant = mine.substring(0, 32).trim();
                // System.out.println("EMAIL ID: " + lineIwant);
                String emailreg = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
                Boolean b = lineIwant.matches(emailreg);

                if (b.toString() == "false") {
                    System.out.println(filedel[o]);
                    fsdel.close();
                    //brdel.close();
                    filedel[o].delete();

                }

This piece of code has been working fine until one file appeared with an email Id :

textsam.textsample@somedomain.co.uk

The file was deleted as one that does not have a valid email address. Can someone please help me on how to include the above email address as a valid one?

Why are you limiting the email address to 32 characters ? The above is 34 characters, but you limit it via

String lineIwant = mine.substring(0, 32).trim();

See also this SO question and the answers and this web page discussing email address regexps (it's considerably more complicated than what you're doing currently, and I would rethink your approach re. using regexps)

I believe you this is an error occurred due to limitation of characters. Always leave atleast 50 characters for an email address. My personal practice is 100, Also consider using Regular expressions inbuilt on the Microsoft visual studio, it should make things much easier for you.

Here's a link

http://msdn.microsoft.com/en-gb/library/system.text.regularexpressions.regex.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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