Logo with initials
Click me x5 ↓

How to use curly brackets with regular expressions

Last updated: March 1st, 2023

I was cleaning up a bad TSV the other day, and for some reason I needed a regular expression to select only 2 whitespaces. My problem was that the usual backslash syntax that I’m used to (\s) will select whitespace, tabs and line breaks.

So that’s how I discovered curly brackets in regex (or curly braces for you Americans.) Curly brackets allow you to capture a specific number of things.

So, here’s how to capture only 2 whitespaces in JavaScript:

const regex = /[ ]{2}/g;
/// Feel free to change the number.

For 2 or more spaces, add a comma.

const regex = /[ ]{2,}/g;

The comma between the curly brackets gives you even more control over how many times the specific character should occur:

  • {3,} means 3 or more
  • {,3} means 3 or less
  • {3,6} means between 3 and 6

Note that you don’t need the square brackets (also called character classes), you can use normal regexp syntax (like backslashes, etc) before curly brackets and it will work.

Let’s capture 3 digits for example:

const regex = /\d{3}/g;

My first reflex for the code above would be to put a quantifier (like an asterisk) like this /\d{3}/g but it’s not needed.

It works on the usual combo of alphanumeric characters too, like

a-zA-Z0-9{3}

Regular capturing groups with parentheses and question marks work too, so a quick and dirty regex to capture a UK postcode would look like this:

const regex = /[A-Z](\d*){2}/g;

The great thing about this syntax is that it works in most programming languages, whether it’s in JavaScript, Python, Rust, Java, Perl, etc.

I hope you find it useful too. Good luck with your regex adventures.

Share