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: adasd457@sdjf45.idie

1.Don't allow special character

2.don't allow number after . value(ex-sdf@sadf.co333)

user8119542
  • 97
  • 1
  • 7

1 Answers1

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:

  • emailRegularExpression.test("adasd457@sdjf45.idie"): true
  • emailRegularExpression.test("ex-sdf@sadf.co333"): false
  • emailRegularExpression.test("j²coolio@sadf.co333"): false (special character)
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • 1
    Don't use the `RegExp` constructor, it recompiles the regular expression every time that line is invoked whereas a `RegExp` literal like [here](https://stackoverflow.com/questions/52298131/how-to-convert-c-sharp-regex-to-typescript-regex?noredirect=1#comment91544552_52298131) will be statically compiled. – Patrick Roberts Sep 12 '18 at 15:23
  • @PatrickRoberts: Thanks for pointing that out. I updated my answer. – StriplingWarrior Sep 12 '18 at 15:25
  • 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 \ – tatsu Feb 22 '21 at 22:01