0

I am new to angular, i have the c# email regex and i don't know what is the difference between the c# regex and typescript regex. it's not working properly.Thanks in advance

Regex:

EmailRegularExpresssion = @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z-])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$";

Example Email: [email protected]

1.Don't allow special character

2.don't allow number after . value([email protected])

8
  • 1
    It's very difficult to help you without example inputs on which the expression fails. Commented Sep 12, 2018 at 14:58
  • 2
    Can you be more specific than "i not working properly"? For example, strings that you think the regex should accept, but which aren't accepted, or vice versa? And any attempts you've already made (if any) on figuring out what's wrong? Commented Sep 12, 2018 at 14:58
  • Hello, can you give some input and output examples ? Commented Sep 12, 2018 at 15:03
  • 2
    If you are trying to validate an email, angular has an internal directive that do the job for you anyway Commented Sep 12, 2018 at 15:04
  • Your regex doesn't allow for + user part of the e-mail address. It's a valid character, as are many others. Commented Sep 12, 2018 at 15:10

1 Answer 1

3

The C# code you've provided uses C#'s Verbatim string syntax, which doesn't require escaping of backslashes. To convert it to a normal string literal, which would be the same in C# and JavaScript, you can remove the @ symbol at the front and then escape backslashes by adding another backslash before them:

 "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z-])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$"

To use this as a JavaScript Regex, you pass it to the RegExp constructor:

let emailRegularExpression = new RegExp("^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z-])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$");

Or, even better, you can just use JavaScript's literal regex syntax (without escaping backslashes:

let emailRegularExpression = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z-])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;

This works as specified for the cases you've specified:

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

3 Comments

Don't use the RegExp constructor, it recompiles the regular expression every time that line is invoked whereas a RegExp literal like here will be statically compiled.
@PatrickRoberts: Thanks for pointing that out. I updated my answer.
this regex is valid : ^(?=\P{Ll}*\p{Ll})(?=\P{Lu}*\p{Lu})(?=\P{N}*\p{N})(?=[\p{L}\p{N}]*[^\p{L}\p{N}])[\s\S]{8,}$ but when inserted between two / it breaks syntax. wheras your example doesn't. EDIT it seems I have to double the \

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.