Regex patterns

Regex are extremly poweful but there is some truth to the old saying: You had one problem and found out you could solve it with regex and now you have two problems.

Lookahead assertion

User want to escape ’:’ and ’.’ in [ab:1.2:ef]=‘12.3’ => [ab:1.2:ef]=‘12.3’

result = subject.replace(/([:.])(?=[^[\]]*\])/g, '\\$1')

([:.])      Match and remember a dot/colon,
(?=         only if it is followed by:
[^[\]]\*    any number of characters excluding brackets,
\]          followed by a closing bracket.
)           End of lookahead assertion.
Replace tags

Very useful when you modify this depending on your needs.

html.replace(/<[^>]+>/gi, '')
Email regex

Probably the most googled regex. No one knows what the ultimate regex for email is. But here are some. Just make sure users ae not stuck if you use a loose one.

The long one (not the longest by far):


The short one:


Somewhere inbetween:

^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$ or ^[a-zA-Z0-9]+(?:.[a-zA-Z0-9]+)@[a-zA-Z0-9]+(?:.[a-zA-Z0-9]+)$ etc…

Target a tag with a attribute as backreference

…or if double or single qoutes are optional: