Explain Regex Like I'm Five
Electrode Cathode

Electrode Cathode @electrode

Location:
Lagos
Joined:
Dec 17, 2017

Explain Regex Like I'm Five

Publish Date: Aug 30 '18
19 6

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

Comments 6 total

  • Electrode Cathode
    Electrode CathodeAug 30, 2018

    Thanks for the info

  • dean
    deanAug 31, 2018

    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!

    • Electrode Cathode
      Electrode CathodeSep 1, 2018

      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?

Add comment