DEV Community

Electrode Cathode
Electrode Cathode

Posted on

Explain Regex Like I'm Five

I'm still trying hard to understand all what magic they put in the thing that makes it work.

Top comments (6)

Collapse
 
dean profile image
dean

Regular expressions are essentially matchers. They're especially useful for verifying input, and for things like online filters.

For instance, let's say I wanted to know if the user submitted a valid united states phone number in the format ###-###-####. I could easy verify with this expression:
\d\d\d-\d\d\d-\d\d\d\d

I could make this a little more readable:
\d{3}-\d{3}-\d{4}

(The \d means "digit" and the {#} means "repeated this many times")

Let's try another one, which will try to block the S-word and some of it's variants:
[sS5]+[hH]+[iI1]+[tT7]+

(The [...] means "any of these letters" and the + means "at least once in a row")

So this regex would match "Sh17" and "sHi7" and "SssshII1It" which is extremely useful for places like online forums which need to be kid-friendly.

There's more complex regular expressions for stuff like websites, which allows you to do something like:

comment = comment.replaceAll("(website regex)", "<a href=\"$1\">$1</a>");

That's some quick code that, given a regular expression that matches websites, will replace every instance of the website with a link to the website!

Collapse
 
electrode profile image
Electrode Cathode

Its all clear to me now, so id there some kind of glossary containing all these expressions?
or how did you know d is for digits and [...] means any of these letters?

Collapse
 
dean profile image
dean

If you Google "regex cheat sheet" there's plenty out there! Each languages implementation of regexes are a little different though.

Here's a nice one gist.github.com/vitorbritto/9ff58e...

Thread Thread
 
electrode profile image
Electrode Cathode

Thank you very much.

Collapse
 
electrode profile image
Electrode Cathode

Thanks for the info