I am trying to accept \\ and / before the @ symbol in our email like usernames.
Below is the current Regex that we are using:
^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$
The reason why I only want to allow double backslash is that I want the string to be escaped by the time I use this regex to validate if it is a valid username.
Valid and Invalid Use Cases:
hello\\world@email.comis valid.hello\world@email.comis invalid.hello/world@gmil.comis valid.hello@email.comis valid.
I have tried the following regular expression but it allowed single backslash also:
^([\w-(\\\\)/\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$
Answer
How it should be escaped depends a little on what language you are using, but here you go:
^(([-\w\/\.]|\\\\)+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$
All I did is add a forward slash in the first group \/ and add two back slashes as an alternative |\\\\.
Here is the C# escaped version:
^(([-\\w\\/\\.]|\\\\\\\\)+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$
No comments:
Post a Comment