🍍 koscielniak.pro

⌘+K

Search IconIcon to open search

Regular Expressions Cheatsheet

Last updated Unknown Edit Source

Regular expression - a sequence of characters representing a pattern.

They are pretty hard to maintain:

If you’ll use regular expression to solve a problem, you’ll have two problems.

Regular expressions are case-sensitive by default.

We need to keep in mind the special characters, like .. (metacharacters).

It’s generally better to re-use the regular expressions available over the Internet, as they are pretty tricky to write and maintain. The bugs in these are probably fixed by the community already.

# Metacharacters

metacharmeaning
.any character
^match only the pattern that occures at the beginning of the line
$match only the pattern that occures at the end of the line
\wword (a-z, A-Z, 0-9, _)
\Wnot word (plus \n)
\nnew line
\ttab
\ddigit
\d\dnumber of 2 digits
\d\d-\d\d\dPolish zip code (12-345)

# Operators

operatormeaning
+at least one occurence
\d+at least one digit
*0 or more occurences
{3}exactly 3 occurences
\d{3}exactly 3 digits
{1,3}between 1 and 3 occurences
[]set of matched characters or range
[ -]either space or - or both
[A-Z]letter between A-Z
(-<pipe> )space OR - (<pipe> => OR)
\escape metacharacters
\.dot (escaped .)
^negation

# Flags

flagmeaning
gmatch all occurences
mmake ^ and $ work in every line (not only first/last ones)
imake the expression case-insensitive

# Groups

operatormeaning
()encapsulate expression in a group
(?:)not group?

# Groups indexing

Groups are indexed from 1. $2 - first group in matched pattern

# Examples

# Phone number

1
2
3
4
5
6
(\d{3}(-1 )){2}\d{3}
- (\d{3}(-1 )){2} - match (123- | 123<space>) twice
- then match last (123)

123-456-789
123 456 789

# Email

There’s no perfect email regex, but this one is pretty close.

# CSS rgb/rgba function

1
^rgba?\([0-9, ]+\);$

# CSS rgb() and rgba() values

1
^rgba?\((\d{1,3}(?:,\s?\d{1,3}){2}(?:,\s?[0-1]\.?\d?)?)?\);?$

Matches:

# Apps

# Ideas to explore

Regular Expressions aren’t usable only for programming. They can be used to:

# Resources


index_