Arpita Dutta
Arpita Dutta

Reputation: 291

Regex to restrict special characters in the beginning of an email address

PFB the regex. I want to make sure that the regex should not contain any special character just after @ and just before. In-between it can allow any combination.

The regex I have now:

@"^[^\W_](?:[\w.-]*[^\W_])?@(([a-zA-Z0-9]+)(\.))([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$"))"

For example, the regex should not match

[email protected]
[email protected]
SSDFF-SAF@-_.SAVAVSAV-_.IP

Upvotes: 3

Views: 3469

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626950

Since you consider _ special, I'd recommend using [^\W_] at the beginning and then rearrange the starting part a bit. To prevent a special char before a @, just make sure there is a letter or digit there. I also recommend to remove redundant capturing groups/convert them into non-capturing:

@"^[^\W_](?:[\w.-]*[^\W_])?@(?:\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.|(?:[\w-]+\.)+)(?:[a-zA-Z]{2,3}|[0-9]{1,3})\]?$"

Here is a demo of how this regex matches now.

The [^\W_](?:[\w.-]*[^\W_])? matches:

  • [^\W_] - a digit or a letter only
  • (?:[\w.-]*[^\W_])? - a 1 or 0 occurrences of:
    • [\w.-]* - 0+ letters, digits, _, . and -
    • [^\W_] - a digit or a letter only

Upvotes: 3

Jonathan Twite
Jonathan Twite

Reputation: 952

Change the initial [\w-\.]+ for [A-Za-z0-9\-\.]+.

Note that this excludes many acceptable email addresses.

Update

As pointed out, [A-Za-z0-9] is not an exact translation of \w. However, you appear to have a specific definition as to what you consider special characters and so it is probably easier for you to define within the square brackets what you class as allowable.

Upvotes: 1

Related Questions