0

I have this to big regex that I use in JavaScript to validate email address.

/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

When I try to used them in Java, I get syntax errors.

Unclosed character class near index 154 /^(([^<>()[]\.,;:\s@\"]+(.[^<>()[]\.,;:\s@\"]+)*)|(\".+\"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/ ^

I'm using http://www.regexplanet.com/ to test the regex.

Is there any way to convert or escape chars or something like this? Thanks!

8
  • 1
    you do know it's very hard to get a regex to validate an email (as per RFC 822), right? ex-parrot.com/pdw/Mail-RFC822-Address.html. See discussion here: stackoverflow.com/questions/201323/… Commented Nov 26, 2015 at 18:15
  • Tried using input type="email" ? Commented Nov 26, 2015 at 18:19
  • 1
    @guest271314 Still need server-side validation. Commented Nov 26, 2015 at 18:23
  • 3
    @guest271314 If a web form was the only way someone could send data to the server, sure. But it isn't, and believing it is leaves you wide open to the most trivial of hacks. Commented Nov 26, 2015 at 18:37
  • 2
    @guest271314 Use both client-side validation (for immediate, high-level feedback) and server-side validation to protect your data. Commented Nov 26, 2015 at 18:56

2 Answers 2

1

This is the JS regex as a Java string literal:

"(([^<>()\\[\\].,;:\\s@\"]+(\\.[^<>()\\[\\].,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,}))"

The anchors (^$) have been removed, since they're not needed when calling matches().

All \, except \", have been doubled.

[ inside a class ([]) needed escaping, so escape added (\\[).

. inside a class ([]) don't need escaping, so escape removed.

- inside a class ([]) don't need escaping if placed last, so moved to end.

Sign up to request clarification or add additional context in comments.

Comments

1

I scaped some characters, the result is this:

/^
    (
        (
            [^<>()\[\]\\.,;:\s@\"]+
            (\.[^<>()\[\]\\.,;:\s@\"]+)*
        )
        |
        (
            \".+\"
        )
    )

    @

    (
        (\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])
        |
        (([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,})
    )

$/

regexplanet.com:link

Seems like the problem was that there are some [ unescaped.

Anyway I encorage you to see this question: What-is-the-best-java-email-address-validation-method

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.