Sunday 13 January 2019

c# - How to allow only double backslash in email with Regex?



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:




  1. hello\\world@email.com is valid.


  2. hello\world@email.com is invalid.

  3. hello/world@gmil.com is valid.

  4. hello@email.com is 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})(\]?)$


See it in action



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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...