DEV Community

Mohammad Kareem
Mohammad Kareem

Posted on

Learn Enough Regex Without Losing Your Mind

I fully understand that Regex is such a complex and borderline witchcraft topic to the average dev ( myself included ) but trust me it's extremely powerful and can solve issues in some cases so i decided to put together this simple blog to try my best to teach you enough regex without losing your mind :)

REGEX BASICS FOR THE CURIOUS OF SOUL

So to be completely transparent with you if i could write 20 lines of code in order to avoid writing a regex i'd do it BUT it's still useful in some use cases and tbh a valid solution so let's learn the basics and enough to work with regex

this blog will be programming language agnostic as i won't use any as an example but stick to the syntax itself rather than using it in a programming language

WHAT IS REGEX AND WHY DO I NEED IT

Regex is text pattern matching that helps us match pieces of text according to a pattern we specify using special operators, so arranging those regex operators in a way to do any text processing task you could imagine

Examples include : email validation, phone number validation, postal code validation, credit card validation, etc etc……

HOW CAN I PRACTISE MY REGEX ?

we’re gonna use this online tool to help us test and visualize our regex in real time, it’s an amazingly great tool to learn since we can see our mistakes as well as finding out why such pattern worked

We’re gonna build few examples to learn as much regex as we need to start and it’ll be just enough for now until we run into super complex stuff

  • phone number example
  • email example
  • price tag example
  • DD/MM/YYYY date format example

OUR CHEATSHEET FOR THIS TUTORIAL

To stay focused we're gonna cover these operators as i believe they're more than enough to wrap your head around regex but it goes without saying that regex can get pretty complicated but we're only interested in pretty basic pattern matching stuff so here's our little cheatsheet :

  1. ^ beginning of a line
  2. $ end of the line
  3. [] grouping — basically means “ranges” like [a-z], [0–9]
  4. {} means how many times you’d like this pattern to occur
  5. ? one or zero times aka optional operator
  6. + at least one or more times, basically means i don’t care how many time this pattern occurs
  7. * zero or more times
  8. \w will match every letter, number and underscore
  9. \d will match single digits only
  10. \s space
  11. \t tab
  12. / escape special characters — in case we wanna match an actual dollar sign for example

REGEX HELLO WORLD

So the most basic regex we can write is the text itself ! suppose you wanna extract a name for example “Bridget”, you can literally write Bridget so let’s jump to our online tool and find out

regex hello world

USING MORE OPERATORS

using more operators

Don’t panic 😄 there’s nothing fancy going on at all there, so our pattern now says “start the line, find Bridget, close the line”, as discussed earlier the carrot ^ means the line begins with……everything that follows and the $ means the end of the line, so again, find me this pattern where the line starts with the word Bridget and the line ends

INTRODUCING GROUPS TO MATCH MORE PATTERNS

OK so now our regex only matches this one word…..but what if we wanna match more ? We’re not gonna write every name are we 😂

For that we’re gonna use the square brackets to use grouping, which means find me a pattern that consist of this group of letters or numbers or special characters, so let’s write a regex that simply matches any given first name then we’ll extend it to include more words separated by spaces basically to simulate a full name

full name example

Now pay attention to the visualization and how we now have two “blocks” basically, it simply says, find me this pattern where there is a small or a capital letter infinitely followed by a space followed by the same pattern for the block prior

quick note, English is my second language so my explanation can be a little misunderstood or inaccurate so please pardon me, I’ll try to explain as simple as possible and provide visuals

USING REGEX TO VALIDATE A US PHONE NUMBER

Now that we know some regex let’s try to validate a phone number, so a US phone number consists of 3-digit area code followed by another 3 digits that represent a central office, followed by 4digits that represent the subscriber number so it should look like 202–555–0160 ( a fake number btw ) and we’ll include the dashes too

phone number validation

See how easy it is now :) isn’t regex so much fun so far 😍, notice how we simply added the dashes as they don’t represent anything in regex so they’re treated literally as they look, you notice how we so far “draw” how our data should look like ? I really hope it clicked :)

EMAIL VALIDATION USING REGEX

Now we’re gonna do a classic regex which is validating an email address but bear in mind that this is pretty basic as i imagine real production level regex patterns will be far more complex but we’re just tinkering around for fun :)

This example will demonstrate how can we add more than just numbers and letters to our group

email validation

EXTRACTING A PRICE FROM A WEBPAGE WITH REGEX

Ok now a more fun example ( hopefully so ) so let's say you're scraping amazon or whatever website and you needed to extract a price for something, well regex makes this extremely easy plus we'll get to learn about character escaping since $ is already a regex operator

price validation using regex

translation is: it begins with a digit (0-9) followed by a dot ( yes we had to escape that too ) followed by another number and lastly a dollar sign

But you'll notice that our regex only applies to prices with a floating point aka not whole numbers like 14$ so how do we fix that ?

USING THE ? OPERATOR TO INDICATE THE OPTIONAL PRESENCE OF A PATTERN

To address the mentioned issue above well use the ? operator to signal to our regex expression that the second half of the price is optional in case we run into whole numbers so let's quickly fix our regex

idek anymore

FINAL NOTES

As in anything software related, you NEED to practise more to the point where the concept becomes natural to you and a thing of a habit so use the online tool i mentioned above and you can always learn more and if you find yourself in need to learn more regex then go for it cause the best way to learn something besides practise is to actually use the new knowledge in solving your own issues

Thank you so much if you've made it this far and i pray to God i can always bring you the most useful of content and be able to give back to the online community that made me who i am today

Top comments (0)