Intro to Regex for Web Developers
Chris Achard

Chris Achard @chrisachard

About: I'm trying to teach everything I know at chrisachard.com Instructor at egghead.io Mostly, I use JS, React, Rails, and Node

Location:
USA
Joined:
Aug 14, 2019

Intro to Regex for Web Developers

Publish Date: Oct 8 '19
441 36

This was originally posted as a twitter thread: https://twitter.com/chrisachard/status/1181583499112976384

1.

Regular expressions find parts of a string that match a pattern

In JavaScript they're created in between forward slashes //, or with new RegExp()

and then used in methods like match, test, or replace

You can define the regex beforehand, or directly when calling the method

new regex

2.

Match individual characters one at a time,

or put multiple characters in square brackets [] to capture any that match

Capture a range of characters with a hyphen -

square brackets and hyphen

3.

Add optional flags to the end of a regex to modify how the matcher works.

In JavaScript, these flags are:

i = case insensitive
m = multi line matching
g = global match (find all, instead of find one)

regex flag modifiers

4.

Using a caret ^ at the start means "start of string"

Using a dollar sign $ at the end means "end of string"

Start putting groups of matches together to match longer strings

caret dollar sign, group matches together

5.

Use wildcards and special escaped characters to match larger classes of characters

. = any character except line break

\d = digit
\D = NOT a digit

\s = white space
\S = any NON white space

\n new line

wildcards

6.

Match only certain counts of matched characters or groups with quantifiers

  • = zero or more
  • = one more more ? = 0 or 1 {3} = exactly 3 times {2, 4} = two, three, or four times {2,} = two or more times

quantifiers

7.

Use parens () to capture in a group

match will return the full match plus the groups, unless you use the g flag

Use the pipe operator | inside of parens () to specify what that group matches

| = or

parens to capture group

8.

To match special characters, escape them with a backslash \

Special characters in JS regex are: ^ $ \ . * + ? ( ) [ ] { } |

So to match an asterisks, you'd use:

\*

Instead of just *

special characters

9.

To match anything BUT a certain character, use a caret ^ inside of square brackets

This means ^ has two meanings, which can be confusing.

It means both "start of string" when it is at the front of a regex, and "not this character" when used inside of square brackets.

caret to mean NOT

10.

Regexs can be used to find and match all sort of things, from urls to filenames

HOWEVER! be careful if you try to use regexs for really complex tasks, such as parsing emails (which get really confusing, really fast), or HTML (which is not a regular language, and so can't be fully parsed by a regular expression)

There is (of course) much more to regex like lazy vs greedy, lookahead, and capturing

but most of what web developers want to do with regular expressions can use just these base building blocks.

I'm already writing a follow up post with a bunch of real world regex use cases 🎉

 

Like this post?

Find more on twitter: @chrisachard
Or join the newsletter 📬 https://chrisachard.com/newsletter/

Thanks for reading!

Comments 36 total

  • Simon Holdorf
    Simon HoldorfOct 8, 2019

    Nice one, Chris

    • Chris Achard
      Chris AchardOct 8, 2019

      Thanks! While writing it I realized that regex is just really complicated 😅 I had trouble distilling it down into a single "intro" post.

      I do have ideas about a page with real examples and explanations though that I think will help - so I'm working on that :)

      • Simon Holdorf
        Simon HoldorfOct 8, 2019

        Yeah I often have those ideas where I think "okay I am just going to make it easy and understandable" and then "why the heck has this to be so complicated" :)

  • webdeasy.de
    webdeasy.deOct 8, 2019

    Great summary for beginners, good job! 😇

  • Dmitry Lukanin
    Dmitry LukaninOct 8, 2019

    I am using regex for years and still im like "i have no idea what im doing" in it. Regex is really hard to master. Thank you.

    • Chris Achard
      Chris AchardOct 8, 2019

      Yes, it is for sure :) I still am not good with lookaheads, etc... but thankfully regex is still really useful even with just the basics!

  • danielvdbos
    danielvdbosOct 8, 2019

    I have looked so hard and long the past year for an explanation of regex that I would understand and this is the first one that put everything I need to know together.

    I really love the format of examples of how to use the theory you mention, so I can see how it will work, since most explanation either show the theory or just a bunch of examples.

    • Chris Achard
      Chris AchardOct 8, 2019

      Glad you liked it! Yeah, it turns out regex is really complicated, heh... there are so many little rules - it's like its own little language all smushed together into a single line :)

  • Max Antonucci
    Max AntonucciOct 8, 2019

    I recommend learning Regex if for no other reason than pulling off complex searches (and search and replaces) in code editors. A few Regex tricks can turn an otherwise tiresome "find, check, and replace in all the files" to an automated search and replace function. Great to see more content helpers coders get to that point!

    • Chris Achard
      Chris AchardOct 8, 2019

      Yes! This is probably my number one use case as well; that, and trying to extract data from HTML or other messy data 😯 which I know, I know, isn't a good use case (I even say so in the post!) but for one-off tasks it's really powerful.

  • jreckers
    jreckersOct 8, 2019

    Really, really, nice explanations with examples!

  • MetalCar
    MetalCarOct 9, 2019

    I'm glad I found this one. Finally it's possible for everyone to understand regex :D I like your summary, Chris.

    I can recommend this tool/website for testing and building regex. It helped me a lot: regex101.com/

    • Chris Achard
      Chris AchardOct 9, 2019

      Great! Glad it helped.

      That's a nice site - thanks for the link!

  • Max Ong Zong Bao
    Max Ong Zong BaoOct 9, 2019

    I like Regex since I tried to create a validator for checking my identity card in my country back in the day.

    I think it is worth to mention that there are multiple variants of Regex implementations like the one in Perl, Linux or PHP I think.

    Thus it depends on the developer. It might make sense to adopt certain variant of Regex to get what you need.

    • Chris Achard
      Chris AchardOct 9, 2019

      Yes, that's a good point. The major points are the same across languages, but there are some differences (how the flags behave for example) - so if you're using the more advanced features, then watch out for cross language differences.

  • Kavinda Jayakody
    Kavinda JayakodyOct 9, 2019

    This is what i always wanted <3. Tried hard in the past to understand regex and this did the work!

  • Quinn Kleinfelter
    Quinn KleinfelterOct 9, 2019

    Just a note, under part 8, your escape sequence seems to have been escaped into just a single *, so its missing the backslash now.

    • Chris Achard
      Chris AchardOct 9, 2019

      Oh, whoops! Good catch... turns out markdown will take \* as an escaped *, so I needed double backslash there. Thanks!

  • Abdelrahman Ahmed
    Abdelrahman AhmedOct 9, 2019

    Very nicely explained. First time to understand what Regex is about. Thanks.

  • Ori Volfovitch
    Ori VolfovitchOct 10, 2019

    This is the best REGEX explanation + examples I have ever came across on the web!

    Thank you!!

  • Luís Ferreira
    Luís FerreiraOct 14, 2019

    What a great post. I am saving this for the future and sharing it with my colleagues. Thank you!

  • Nick Taylor
    Nick TaylorOct 15, 2019

    Great read Chris!

    One resource I found super useful, once I dove into regexes more was the Mastering Regular Expressions book. I have the 2nd edition, but there appears to be a 3rd edition out.

    Looking forward to your next post!

  • Mark Roeling
    Mark RoelingOct 15, 2019

    Great building up of the level of the regex's!
    I kinda started my regex knowledge from regular-expressions.info/, the guys that also made RegexBuddy. Very detailed and with a lot of simple examples.

    And if you really want to get a feeling for regex's, try regexcrossword.com/.

  • icaropnbr
    icaropnbrOct 15, 2019

    Nice job! Helped a lot!

    ;)

  • Adithya Sreyaj
    Adithya SreyajOct 15, 2019

    Regex has always been something which is hard to grasp(atleast for me)....
    This post proves it to be wrong.

    Excellent Post Chris.
    Thanks✌️

    • Chris Achard
      Chris AchardOct 15, 2019

      Glad it could help!

      Yeah, it's often disheartening to see really complex regexes and get totally lost... but just a few basics can get you pretty far!

      I still get lost in really complex regexes though 😂 especially when they start involving capturing groups or lookahead, etc.

  • oscar6echo
    oscar6echoJan 26, 2020

    Very useful summary.

  • Tápai Balázs
    Tápai BalázsFeb 21, 2020

    Thank you! I've learned a lot from this post. :)

  • Christina Blakely
    Christina BlakelyMar 17, 2020

    This was the best intro guide to regex I could find, thank you!

  • codechunker
    codechunkerApr 28, 2020

    This is such an awesome post. Thank you so much. There is also one for Java dev.to/codechunker/introduction-to...

Add comment