Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics

Dashboard
Notifications
Mark all as read
Q&A

How to match standard email addresses with regex?

+5
−0

I want to match standard email syntax (lowercased English, numbers and perhaps also some hyphens and underscores) with regex for a sed operation that matches and changes a single email address inside a file.

The following code failed:

read new_email_address
sed -i 's/[a-zA-Z0-9-_]*@[a-zA-Z0-9-_]*.[a-z]*/"'"${new_email_address}"'"/g' FILE

I know its problematic in the sense that files can have two or more email addresses and a global change is dangerous, but this is primarily just for learning and practice regex and sed.

Why does this post require moderator attention?
You might want to add some details to your flag.
Why should this post be closed?

4 comments

I think "traditional" is more appropriate than "standard" (see International email ). Alexei‭ 28 days ago

sed is used for simple search and replace, and in most cases, it is just used to remove/replace a part of a line after a certain char. I suggest you re-consider the requirements and come up with a more concrete problem statement than "matching emails with POSIX regex". wiktor.stribizew‭ 23 days ago

@wiktor.stribizew‭ hello, I misunderstand the last part of your comment; I very much agree that sed is used (or should be used) for simple match and replace operations as you have described but because I didn't mention POSIX regex at all in my question I can say that my original goal here was to match quite simple email patterns... JohnDoea‭ 23 days ago

sed only supports POSIX regex flavor. What I mean is you do not need any super-complex regex in case you want to replace an email address in a E-mail: [email protected] string (a line in a file) since you may just use sed "s/E-mail: .*/E-mail: ${new_email_address}/" file. Matching arbitrary emails is next to impossible with a "simple" email pattern. If you mean some specific format, you should explain this format in the question. wiktor.stribizew‭ 21 days ago

1 answer

+5
−0

Matching a valid email address can be as complicated as you want it to be.

If you want to be compliant with RFC 5322, the regex will be a monster (see below).

But if you want a subset of it, with predefined arbitrary rules, then your monster will be a little less scary.

Considering the simple rules you stated (lowercased English, numbers and perhaps also some hyphens and underscores), it could be something like this:

sed -E 's/[a-z0-9_\-][email protected][a-z0-9._\-]+\.[a-z]{2,}/"'"${new_email_address}"'"/g' FILE

I used -E option to enable ERE (Extended Regular Expressions), because without it, quantifiers such as * and + need to be written as \* and \+, which is - IMO - annoying. By using -E, the behaviour becomes similar to other engines (in which \+ is the character + itself, and + is the quantifier).

As you want only lowercase letters, I removed the A-Z interval. I also changed the * quantifier to + (the former stands for "zero or more occurrences", so it also matches "nothing" (zero characters); the latter stands for "one or more occurrences", so it must have at least one character to match it). You used * everywhere, which means your regex will also match @. (as it matches zero characters before and after @, and also zero characters after the dot).

And note that the dot must be escaped when it's not inside [ ]: inside brackets, most meta characters don't need to be escaped - the exception being the - character because it has a special meaning (it creates intervals, such as a-z to match all letters between a and z). Although some engines recognize that, when there's a - in the end of the list (followed by ]), it doesn't need to be escaped - but I escaped anyway.

As you didn't escape the dot that's outside brackets, it actually matches any character, so your regex will match @ followed by any character.

In the domain part (after @), I included . in the valid characters, so it will match domains with multiple dots, such as "whatever.company.gov", and in the end I added a dot followed by at least 2 letters ([a-z]{2,}), so it'll kinda force it to end in a top level domain (or something that looks like one).


Of course this is a very naive approach.

[a-z0-9_\-] matches any character in the list, and [a-z0-9_\-]+ matches one or more of those characteres, so it also matches a sequence of _ or -. The same applies to [a-z0-9._\-]+, so the regex above considers that [email protected] is a valid email.

And now we face the classic trade-off when it comes to regular expressions.

If you want to be more precise and avoid those "weird" cases, the regex will become more complex. But the more complex, the harder it is to understand and maintain it. In the link I mentioned above you can see how the regex complexity increases for each special case we add to it. It ends up with this:

\A(?:[a-z0-9!#$%&'*+/=?^_‘{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_‘{|}~-]+)*
 |  "(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]
      |  \\[\x01-\x09\x0b\x0c\x0e-\x7f])*")
@ (?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
  |  \[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}
       (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:
          (?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]
          |  \\[\x01-\x09\x0b\x0c\x0e-\x7f])+)
     \])\z

Which I don't even know if it works with sed - and even if it works, would it be worth using?

Ok, maybe you don't need to be fully compliant with RFC 5322, but also don't want to accept [email protected]. Then you could change the regex to:

[a-z0-9]+([_.\-][a-z0-9]+)*@[a-z0-9._-]+\.[a-z]{2,}

Now, before the @, I'm saying that the email can start with one or more letters/numbers, and it might have a sequence of zero or more "dot/underscore/hyphen followed by letters or numbers". This would allow john.doe or john.doe-smith_whatever, but not john...doe nor -_-.

And for each part, you can increase the complexity, depending on what you want the regex to match or to discard (in the link mentioned, you can see lots of options for different approaches).

In the end, it's up to you, to choose between a regex that gets lots of false positives but it's easier to understand and maintain, and a more complex, but more assertive one.

Why does this post require moderator attention?
You might want to add some details to your flag.

1 comment

That is a scary monster indeed. :-) Monica Cellio‭ 26 days ago

Sign up to answer this question »