Regular expressions. If you know how to use them, they are awesome and powerful. If not, they look like an alien language that needs to be decoded. Either way, this guide will cover the basics of regexes and how they are used to make the life of a programmer easier. We will then go over the basic & extended set and how they can be used in Python and terminal. By the end, you’ll have enough regex know-how to step up your everyday coding.


The Basics

Regular expressions are a way to search for patterns in data sets. It is not a programming language on its own, but all major languages have a regex engine built-in for you to utilize.

What is a regular expression anyway?

“A regular expression is a sequence of characters that define a search pattern.” — Wikipedia

The “sequence of characters” are regex syntax, and if you’ve ever seen it you know how foreign it is to read, let alone understand, especially at first. For example:

_^\(?[0-9]{3}\)?[\-\s]?[0-9]{3}[\-\s]?[0-9]{4}$_

At first glance, this can be pretty overwhelming. Most of us don’t want to even try and figure it out. But, it’s just an expression to match a phone number. We’ll break this down in-depth later in the article, so don’t worry if you don’t understand it right now.

When to, and when not to, use regexes

Regexes are useful to programmatically:

  • Find patterns and matches in data sets: Whether it’s a .csv or .txt, they’ve got you covered
  • Validate forms and inputs: Do this on the frontend before you submit a form to make sure there are no issues behind the scenes once it’s been sent.
  • Scrape information from the web: Looking to scrape every link (<a></a>) off of a webpage? There’s an expression for that.

What are the limitations of regular expressions?

  • Regular expressions are not a programming language. They are tools and all major languages utilize them.
  • Difficult to read. Especially if you’re not familiar with them, it’s pretty intimidating and most people, myself included, tend to stay away from them for as long as possible.
  • Can be difficult to write correctly, even if you know what you’re doing. Sometimes getting it to work exactly how you want takes more than a few tries.

#regular-expressions #terminal #programming #regex #python

Your Guide to Regular Expressions in Python and Terminal
2.70 GEEK