RegEx#
#
Introduction#
This is a quick cheat sheet to getting started with regular expressions.
Regex in Python (cheatsheets.zip)
Regex in JavaScript (cheatsheets.zip)
Regex in PHP (cheatsheets.zip)
Regex in Java (cheatsheets.zip)
Regex in MySQL (cheatsheets.zip)
Online regex tester (regex101.com)
Character Classes#
Pattern |
Description |
|---|---|
|
A single character of: |
|
A character except: |
|
A character in the range: |
|
A character not in the range: |
|
A digit in the range: |
|
A character in the range: |
|
A character in the range: |
Quantifiers#
Pattern |
Description |
|---|---|
|
Zero or one of a |
|
Zero or more of a |
|
One or more of a |
|
One or more of 0-9 |
|
Exactly 3 of a |
|
3 or more of a |
|
Between 3 and 6 of a |
|
Greedy quantifier |
|
Lazy quantifier |
|
Possessive quantifier |
Common Metacharacters#
| Pattern | Description |
| ——- | :———————————————————– | ——————————————– |
| ^ | Matches the start of a string. |
| { | Starts a quantifier for the number of occurrences. |
| + | Matches one or more of the preceding element. |
| < | Not a standard regex meta character (commonly used in HTML). |
| [ | Starts a character class. |
| * | Matches zero or more of the preceding element. |
| ) | Ends a capturing group. |
| > | Not a standard regex meta character (commonly used in HTML). |
| . | Matches any character except a newline. |
| ( | Starts a capturing group. |
| | | Acts as a logical OR within a regex pattern. |
| $ | Matches the end of a string. |
| \ | Escapes a meta character, giving it literal meaning. |
| ? | Matches zero or one of the preceding element. |
Escape these special characters with \
Meta Sequences#
Pattern |
Description |
|---|---|
|
Any single character |
|
Any whitespace character |
|
Any non-whitespace character |
|
Any digit, Same as [0-9] |
|
Any non-digit, Same as |
|
Any word character |
|
Any non-word character |
|
Any Unicode sequences, linebreaks included |
|
Match one data unit |
|
Unicode newlines |
|
Vertical whitespace character |
|
Negation of \v - anything except newlines and vertical tabs |
|
Horizontal whitespace character |
|
Negation of \h |
|
Reset match |
|
Match nth subpattern |
|
Unicode property X |
|
Unicode property or script category |
|
Negation of \pX |
|
Negation of \p |
|
Quote; treat as literals |
|
Match subpattern |
|
Match subpattern |
|
Match subpattern |
|
Match nth subpattern |
|
Match nth subpattern |
|
Recurse nth capture group |
|
Recurses nth capture group. |
|
Match nth relative previous subpattern |
|
Recurse nth relative upcoming subpattern |
|
Match nth relative upcoming subpattern |
|
Recurse named capture group |
|
Match previously-named capture group |
|
Recurses named capture group |
|
Hex character YY |
|
Hex character YYYY |
|
Octal character ddd |
|
Control character Y |
|
Backspace character |
|
Makes any character literal |
Anchors#
Pattern |
Description |
|---|---|
|
Start of match |
|
Start of string |
|
End of string |
|
Start of string |
|
End of string |
|
Absolute end of string |
|
A word boundary |
|
Non-word boundary |
Substitution#
Pattern |
Description |
|---|---|
|
Complete match contents |
|
Contents in capture group 1 |
|
Contents in capture group 1 |
|
Contents in capture group |
|
Hexadecimal replacement values |
|
Hexadecimal replacement values |
|
Tab |
|
Carriage return |
|
Newline |
|
Form-feed |
|
Uppercase Transformation |
|
Lowercase Transformation |
|
Terminate any Transformation |
Group Constructs#
Pattern |
Description |
|---|---|
|
Capture everything enclosed |
|
Match either a or b |
|
Match everything enclosed |
|
Atomic group (non-capturing) |
|
Duplicate subpattern group number |
|
Comment |
|
Named Capturing Group |
|
Named Capturing Group |
|
Named Capturing Group |
|
Inline modifiers |
|
Pre-define patterns before using them |
Assertions#
- |
- |
|---|---|
|
Conditional statement |
|
Conditional statement |
|
Recursive Conditional statement |
|
Conditional statement |
|
Lookahead conditional |
|
Lookbehind conditional |
Lookarounds#
- |
- |
|---|---|
|
Positive Lookahead |
|
Negative Lookahead |
|
Positive Lookbehind |
|
Negative Lookbehind |
Lookaround lets you match a group before (lookbehind) or after (lookahead) your main pattern without including it in the result.
Flags/Modifiers#
Pattern |
Description |
|---|---|
|
Global |
|
Multiline |
|
Case insensitive |
|
Ignore whitespace |
|
Single line |
|
Unicode |
|
eXtended |
|
Ungreedy |
|
Anchor |
|
Duplicate group names |
Recurse#
- |
- |
|---|---|
|
Recurse entire pattern |
|
Recurse first subpattern |
|
Recurse first relative subpattern |
|
Recurse subpattern |
|
Match subpattern |
|
Recurse subpattern |
POSIX Character Classes#
Character Class |
Same as |
Meaning |
|---|---|---|
|
|
Letters and digits |
|
|
Letters |
|
|
ASCII codes 0-127 |
|
|
Space or tab only |
|
|
Control characters |
|
|
Decimal digits |
|
|
Visible characters (not space) |
|
|
Lowercase letters |
|
|
Visible characters |
|
|
Visible punctuation characters |
|
|
Whitespace |
|
|
Uppercase letters |
|
|
Word characters |
|
|
Hexadecimal digits |
|
|
Start of word |
|
|
End of word |
Control verb#
- |
- |
|---|---|
|
Control verb |
|
Control verb |
|
Control verb |
|
Control verb |
|
Control verb |
|
Control verb |
|
Control verb |
|
Pattern modifier |
|
Pattern modifier |
|
Pattern modifier |
|
Pattern modifier |
|
Pattern modifier |
|
Line break modifier |
|
Line break modifier |
|
Line break modifier |
|
Line break modifier |
|
Line break modifier |
|
Line break modifier |
|
Line break modifier |
|
Line break modifier |
|
Regex engine modifier |
|
Regex engine modifier |
|
Regex engine modifier |
|
Regex engine modifier |
Regex examples#
Characters#
Pattern |
Matches |
|---|---|
|
Match |
|
Match |
|
Match |
|
Match |
|
Match |
|
Match |
Use \ to search for these special characters:
[ \ ^ $ . | ? * + ( ) { }
Alternatives#
Pattern |
Matches |
|---|---|
|
Match |
|
Match |
|
Match |
Order longer to shorter when alternatives overlap
Character classes#
Pattern |
Matches |
|---|---|
|
Match any vowel |
|
Match a NON vowel |
|
Match |
|
Match |
|
Match any letter or digit |
|
Match any Unicode Hàn (中文) |
In [ ] always escape . \ ] and sometimes ^ - .
Shorthand classes#
Pattern |
Meaning |
|---|---|
|
“Word” character |
|
Digit |
|
Whitespace |
|
Not word, digit, or whitespace |
|
Means not digit or whitespace, both match |
|
Disallow digit and whitespace |
Occurrences#
Pattern |
Matches |
|---|---|
|
Match |
|
Match |
|
Match 1 or more letters |
|
Match a SSN |
|
Match a UW NetID |
Greedy versus lazy#
Pattern |
Meaning |
|---|---|
|
Match as much as possible |
|
Finds 1 big match in |
|
Match as little as possible |
|
Finds 2 matches in < |
Scope#
Pattern |
Meaning |
|---|---|
|
“Word” edge (next to non “word” character) |
|
Word starts with “ring”, ex |
|
Word ends with “ring”, ex |
|
Match single digit |
|
Match 6-letter words |
|
Not word edge |
|
Match |
|
Entire string must be digits |
|
String must have 4-20 letters |
|
String must begin with capital letter |
|
String must end with terminal puncutation |
Modifiers#
Pattern |
Meaning |
|---|---|
|
Ignore case ON / OFF |
|
Match multiple lines (causes . to match newline) |
|
|
|
#free-spacing mode, this EOL comment ignored |
|
free-spacing mode OFF |
/regex/ |
Modify mode for entire string |
Groups#
Pattern |
Meaning |
|---|---|
|
Match |
|
US zip code (”+ 4” optional) |
Parser tries EACH alternative if match fails after group.
Can lead to catastrophic backtracking.
Back references#
Pattern |
Matches |
|---|---|
|
Match |
|
Match non-space, then same twice more |
|
Match doubled words |
Non-capturing group#
Pattern |
Meaning |
|---|---|
|
Faster than: |
Use non-capturing or atomic groups when possible
Atomic groups#
Pattern |
Meaning |
|---|---|
|
Faster than non-capturing |
|
Match |
“id” matches, but \b fails after atomic group, parser doesn’t backtrack into group to retry ‘identity’
If alternatives overlap, order longer to shorter.
Lookaround#
Pattern |
Meaning |
|---|---|
|
Lookahead, if you can find ahead |
|
Lookahead,if you can not find ahead |
|
Lookbehind, if you can find behind |
|
Lookbehind, if you can NOT find behind |
|
Match |
|
Words NOT ending in |
|
Match pre |
|
Words NOT starting with |
|
Match words NOT ending in |
If-then-else#
Match “Mr.” or “Ms.” if word “her” is later in string
M(?(?=.*?\bher\b)s|r)\.
requires lookaround for IF condition
RegEx in Python#
Getting started#
Import the regular expressions module
import re
Examples#
re.search()#
>>> sentence = 'This is a sample string'
>>> bool(re.search(r'this', sentence, flags=re.I))
True
>>> bool(re.search(r'xyz', sentence))
False
re.findall()#
>>> re.findall(r'\bs?pare?\b', 'par spar apparent spare part pare')
['par', 'spar', 'spare', 'pare']
>>> re.findall(r'\b0*[1-9]\d{2,}\b', '0501 035 154 12 26 98234')
['0501', '154', '98234']
re.finditer()#
>>> m_iter = re.finditer(r'[0-9]+', '45 349 651 593 4 204')
>>> [m[0] for m in m_iter if int(m[0]) < 350]
['45', '349', '4', '204']
re.split()#
>>> re.split(r'\d+', 'Sample123string42with777numbers')
['Sample', 'string', 'with', 'numbers']
re.sub()#
>>> ip_lines = "catapults\nconcatenate\ncat"
>>> print(re.sub(r'^', r'* ', ip_lines, flags=re.M))
* catapults
* concatenate
* cat
re.compile()#
>>> pet = re.compile(r'dog')
>>> type(pet)
<class '_sre.SRE_Pattern'>
>>> bool(pet.search('They bought a dog'))
True
>>> bool(pet.search('A cat crossed their path'))
False
Functions#
Function |
Description |
|---|---|
|
Returns a list containing all matches |
|
Return an iterable of match objects (one for each match) |
|
Returns a Match object if there is a match anywhere in the string |
|
Returns a list where the string has been split at each match |
|
Replaces one or many matches with a string |
|
Compile a regular expression pattern for later use |
|
Return string with all non-alphanumerics backslashed |
Flags#
- |
- |
- |
|---|---|---|
|
|
Ignore case |
|
|
Multiline |
|
|
Make |
|
|
Dot matches all (including newline) |
|
|
Make |
|
|
Readable style |
Regex in JavaScript#
test()#
let textA = 'I like APPles very much';
let textB = 'I like APPles';
let regex = /apples$/i;
// Output: false
console.log(regex.test(textA));
// Output: true
console.log(regex.test(textB));
search()#
let text = 'I like APPles very much';
let regexA = /apples/;
let regexB = /apples/i;
// Output: -1
console.log(text.search(regexA));
// Output: 7
console.log(text.search(regexB));
exec()#
let text = 'Do you like apples?';
let regex = /apples/;
// Output: apples
console.log(regex.exec(text)[0]);
// Output: Do you like apples?
console.log(regex.exec(text).input);
match()#
let text = 'Here are apples and apPleS';
let regex = /apples/gi;
// Output: [ "apples", "apPleS" ]
console.log(text.match(regex));
split()#
let text = 'This 593 string will be brok294en at places where d1gits are.';
let regex = /\d+/g;
// Output: [ "This ", " string will be brok", "en at places where d", "gits are." ]
console.log(text.split(regex));
matchAll()#
let regex = /t(e)(st(\d?))/g;
let text = 'test1test2';
let array = [...text.matchAll(regex)];
// Output: ["test1", "e", "st1", "1"]
console.log(array[0]);
// Output: ["test2", "e", "st2", "2"]
console.log(array[1]);
replace()#
let text = 'Do you like aPPles?';
let regex = /apples/i;
// Output: Do you like mangoes?
let result = text.replace(regex, 'mangoes');
console.log(result);
replaceAll()#
let regex = /apples/gi;
let text = 'Here are apples and apPleS';
// Output: Here are mangoes and mangoes
let result = text.replaceAll(regex, 'mangoes');
console.log(result);
Regex in PHP#
Functions#
- |
- |
|---|---|
|
Performs a regex match |
|
Perform a global regular expression match |
|
Perform a regular expression search and replace using a callback |
|
Perform a regular expression search and replace |
|
Splits a string by regex pattern |
|
Returns array entries that match a pattern |
preg_replace#
$str = "Visit Microsoft!";
$regex = "/microsoft/i";
// Output: Visit CheatSheets!
echo preg_replace($regex, "CheatSheets", $str);
preg_match#
$str = "Visit CheatSheets";
$regex = "#cheatsheets#i";
// Output: 1
echo preg_match($regex, $str);
preg_matchall#
$regex = "/[a-zA-Z]+ (\d+)/";
$input_str = "June 24, August 13, and December 30";
if (preg_match_all($regex, $input_str, $matches_out)) {
// Output: 2
echo count($matches_out);
// Output: 3
echo count($matches_out[0]);
// Output: Array("June 24", "August 13", "December 30")
print_r($matches_out[0]);
// Output: Array("24", "13", "30")
print_r($matches_out[1]);
}
preg_grep#
$arr = ["Jane", "jane", "Joan", "JANE"];
$regex = "/Jane/";
// Output: Jane
echo preg_grep($regex, $arr);
preg_split#
$str = "Jane\tKate\nLucy Marion";
$regex = "@\s@";
// Output: Array("Jane", "Kate", "Lucy", "Marion")
print_r(preg_split($regex, $str));
Regex in Java#
Styles#
First way#
Pattern p = Pattern.compile(".s", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("aS");
boolean s1 = m.matches();
System.out.println(s1); // Outputs: true
Second way#
boolean s2 = Pattern.compile("[0-9]+").matcher("123").matches();
System.out.println(s2); // Outputs: true
Third way#
boolean s3 = Pattern.matches(".s", "XXXX");
System.out.println(s3); // Outputs: false
Pattern Fields#
- |
- |
|---|---|
|
Canonical equivalence |
|
Case-insensitive matching |
|
Permits whitespace and comments |
|
Dotall mode |
|
Multiline mode |
|
Unicode-aware case folding |
|
Unix lines mode |
Methods#
Pattern#
Pattern compile(String regex [, int flags])
boolean matches([String regex, ] CharSequence input)
String[] split(String regex [, int limit])
String quote(String s)
Matcher#
int start([int group | String name])
int end([int group | String name])
boolean find([int start])
String group([int group | String name])
Matcher reset()
String#
boolean matches(String regex)
String replaceAll(String regex, String replacement)
String[] split(String regex[, int limit])
There are more methods …
Examples#
Replace sentence:
String regex = "[A-Z\n]{5}$";
String str = "I like APP\nLE";
Pattern p = Pattern.compile(regex, Pattern.MULTILINE);
Matcher m = p.matcher(str);
// Outputs: I like Apple!
System.out.println(m.replaceAll("pple!"));
Array of all matches:
String str = "She sells seashells by the Seashore";
String regex = "\\w*se\\w*";
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);
List<String> matches = new ArrayList<>();
while (m.find()) {
matches.add(m.group());
}
// Outputs: [sells, seashells, Seashore]
System.out.println(matches);
Regex in MySQL#
Functions#
Name |
Description |
|---|---|
|
Whether string matches regex |
|
Starting index of substring matching regex |
|
Whether string matches regex |
|
Replace substrings matching regex |
|
Return substring matching regex |
REGEXP#
expr REGEXP pat
Examples#
mysql> SELECT 'abc' REGEXP '^[a-d]';
1
mysql> SELECT name FROM cities WHERE name REGEXP '^A';
mysql> SELECT name FROM cities WHERE name NOT REGEXP '^A';
mysql> SELECT name FROM cities WHERE name REGEXP 'A|B|R';
mysql> SELECT 'a' REGEXP 'A', 'a' REGEXP BINARY 'A';
1 0
REGEXP_REPLACE#
REGEXP_REPLACE(expr, pat, repl[, pos[, occurrence[, match_type]]])
Examples#
mysql> SELECT REGEXP_REPLACE('a b c', 'b', 'X');
a X c
mysql> SELECT REGEXP_REPLACE('abc ghi', '[a-z]+', 'X', 1, 2);
abc X
REGEXP_SUBSTR#
REGEXP_SUBSTR(expr, pat[, pos[, occurrence[, match_type]]])
Examples#
mysql> SELECT REGEXP_SUBSTR('abc def ghi', '[a-z]+');
abc
mysql> SELECT REGEXP_SUBSTR('abc def ghi', '[a-z]+', 1, 3);
ghi
REGEXP_LIKE#
REGEXP_LIKE(expr, pat[, match_type])
Examples#
mysql> SELECT regexp_like('aba', 'b+')
1
mysql> SELECT regexp_like('aba', 'b{2}')
0
mysql> # i: case-insensitive
mysql> SELECT regexp_like('Abba', 'ABBA', 'i');
1
mysql> # m: multi-line
mysql> SELECT regexp_like('a\nb\nc', '^b$', 'm');
1
REGEXP_INSTR#
REGEXP_INSTR(expr, pat[, pos[, occurrence[, return_option[, match_type]]]])
Examples#
mysql> SELECT regexp_instr('aa aaa aaaa', 'a{3}');
2
mysql> SELECT regexp_instr('abba', 'b{2}', 2);
2
mysql> SELECT regexp_instr('abbabba', 'b{2}', 1, 2);
5
mysql> SELECT regexp_instr('abbabba', 'b{2}', 1, 3, 1);
7