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!

ne1410s
  • 6,864
  • 6
  • 55
  • 61
mauriblint
  • 1,802
  • 2
  • 29
  • 46

3 Answers3

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

Community
  • 1
  • 1
mayo
  • 3,845
  • 1
  • 32
  • 42
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.

Andreas
  • 154,647
  • 11
  • 152
  • 247
0

I share with all the final regex Java email address regex validator

mauriblint
  • 1,802
  • 2
  • 29
  • 46