A quick reference for regular expressions (regex), including symbols, ranges, grouping, assertions and some sa.
This is a quick cheat sheet to getting started with regular expressions.
Regex in JavaScript (quickref.me) Regex in Java (quickref.me)
[abc] β A single character of: a, b or c
[^abc] β A character except: a, b or c
[a-z] β A character in the range: a-z
[^a-z] β A character not in the range: a-z
[0-9] β A digit in the range: 0-9
[a-zA-Z] β A character in the range:a-z or A-Z
[a-zA-Z0-9] β A character in the range: a-z, A-Z or 0-9
a? β Zero or one of a
a* β Zero or more of a
a+ β One or more of a
[0-9]+ β One or more of 0-9
a{3} β Exactly 3 of a
a{3,} β 3 or more of a
a{3,6} β Between 3 and 6 of a
a* β Greedy quantifier
a*? β Lazy quantifier
a*+ β Possessive quantifier
^ { + < [ * ) > . ( | $ \ ?
Escape these special characters with \
. β Any single character
\s β Any whitespace character
\S β Any non-whitespace character
\d β Any digit, Same as [0-9]
\D β Any non-digit, Same as [^0-9]
\w β Any word character
\W β Any non-word character
\X β Any Unicode sequences, linebreaks included
\C β Match one data unit
\R β Unicode newlines
\v β Vertical whitespace character
\V β Negation of \v - anything except newlines and vertical tabs
\h β Horizontal whitespace character
\H β Negation of \h
\K β Reset match
\n β Match nth subpattern
\pX β Unicode property X
\p{...} β Unicode property or script category
\PX β Negation of \pX
\P{...} β Negation of \p
\Q...\E β Quote; treat as literals
\k<name> β Match subpattern name
\k'name' β Match subpattern name
\k{name} β Match subpattern name
\gn β Match nth subpattern
\g{n} β Match nth subpattern
\g<n> β Recurse nth capture group
\g'n' β Recurses nth capture group.
\g{-n} β Match nth relative previous subpattern
\g<+n> β Recurse nth relative upcoming subpattern
\g'+n' β Match nth relative upcoming subpattern
\g'letter' β Recurse named capture group letter
\g{letter} β Match previously-named capture group letter
\g<letter> β Recurses named capture group letter
\xYY β Hex character YY
\x{YYYY} β Hex character YYYY
\ddd β Octal character ddd
\cY β Control character Y
[\b] β Backspace character
\ β Makes any character literal
\G β Start of match
^ β Start of string
$ β End of string
\A β Start of string
\Z β End of string
\z β Absolute end of string
\b β A word boundary
\B β Non-word boundary
\0 β Complete match contents
\1 β Contents in capture group 1
$1 β Contents in capture group 1
${foo} β Contents in capture group foo
\x20 β Hexadecimal replacement values
\x{06fa} β Hexadecimal replacement values
\t β Tab
\r β Carriage return
\n β Newline
\f β Form-feed
\U β Uppercase Transformation
\L β Lowercase Transformation
\E β Terminate any Transformation
(...) β Capture everything enclosed
(a|b) β Match either a or b
(?:...) β Match everything enclosed
(?>...) β Atomic group (non-capturing)
(?|...) β Duplicate subpattern group number
(?#...) β Comment
(?'name'...) β Named Capturing Group
(?<name>...) β Named Capturing Group
(?P<name>...) β Named Capturing Group
(?imsxXU) β Inline modifiers
(?(DEFINE)...) β Pre-define patterns before using them
(?(1)yes|no) β Conditional statement
(?(R)yes|no) β Conditional statement
(?(R#)yes|no) β Recursive Conditional statement
(?(R&name)yes|no) β Conditional statement
(?(?=...)yes|no) β Lookahead conditional
(?(?<=...)yes|no) β Lookbehind conditional
(?=...) β 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.
g β Global
m β Multiline
i β Case insensitive
x β Ignore whitespace
s β Single line
u β Unicode
X β eXtended
U β Ungreedy
A β Anchor
J β Duplicate group names
(?R) β Recurse entire pattern
(?1) β Recurse first subpattern
(?+1) β Recurse first relative subpattern
(?&name) β Recurse subpattern name
(?P=name) β Match subpattern name
(?P>name) β Recurse subpattern name
[[:alnum:]] β [0-9A-Za-z] β Letters and digits
[[:alpha:]] β [A-Za-z] β Letters
[[:ascii:]] β [\x00-\x7F] β ASCII codes 0-127
[[:blank:]] β [\t ] β Space or tab only
[[:cntrl:]] β [\x00-\x1F\x7F] β Control characters
[[:digit:]] β [0-9] β Decimal digits
[[:graph:]] β [[:alnum:][:punct:]] β Visible characters (not space)
[[:lower:]] β [a-z] β Lowercase letters
[[:print:]] β [ -~] == [ [:graph:]] β Visible characters
[[:punct:]] β [!"#$%&β()*+,-./:;<=>?@[]^_`{|}~] β Visible punctuation characters
[[:space:]] β [\t\n\v\f\r ] β Whitespace
[[:upper:]] β [A-Z] β Uppercase letters
[[:word:]] β [0-9A-Za-z_] β Word characters
[[:xdigit:]] β [0-9A-Fa-f] β Hexadecimal digits
[[:<:]] β [\b(?=\w)] β Start of word
[[:>:]] β [\b(?<=\w)] β End of word
(*ACCEPT) β Control verb
(*FAIL) β Control verb
(*MARK:NAME) β Control verb
(*COMMIT) β Control verb
(*PRUNE) β Control verb
(*SKIP) β Control verb
(*THEN) β Control verb
(*UTF) β Pattern modifier
(*UTF8) β Pattern modifier
(*UTF16) β Pattern modifier
(*UTF32) β Pattern modifier
(*UCP) β Pattern modifier
(*CR) β Line break modifier
(*LF) β Line break modifier
(*CRLF) β Line break modifier
(*ANYCRLF) β Line break modifier
(*ANY) β Line break modifier
\R β Line break modifier
(*BSR_ANYCRLF) β Line break modifier
(*BSR_UNICODE) β Line break modifier
(*LIMIT_MATCH=x) β Regex engine modifier
(*LIMIT_RECURSION=d) β Regex engine modifier
(*NO_AUTO_POSSESS) β Regex engine modifier
(*NO_START_OPT) β Regex engine modifier
ring β Match ring springboard etc.
. β Match a, 9, + etc.
h.o β Match hoo, h2o, h/o etc.
ring\? β Match ring?
\(quiet\) β Match (quiet)
c:\\windows β Match c:\windows
Use \ to search for these special characters: [ \ ^ $ . | ? * + ( ) { }
cat|dog β Match cat or dog
id|identity β Match id or identity
identity|id β Match id or identity
Order longer to shorter when alternatives overlap
[aeiou] β Match any vowel
[^aeiou] β Match a NON vowel
r[iau]ng β Match ring, wrangle, sprung, etc.
gr[ae]y β Match gray or grey
[a-zA-Z0-9] β Match any letter or digit
[\u3a00-\ufa99] β Match any Unicode HΓ n (δΈζ)
In [ ] always escape . \ ] and sometimes ^ - .
\w β "Word" character (letter, digit, or underscore)
\d β Digit
\s β Whitespace (space, tab, vtab, newline)
\W, \D, or \S β Not word, digit, or whitespace
[\D\S] β Means not digit or whitespace, both match
[^\d\s] β Disallow digit and whitespace
colou?r β Match color or colour
[BW]ill[ieamy's]* β Match Bill, Willy, William's etc.
[a-zA-Z]+ β Match 1 or more letters
\d{3}-\d{2}-\d{4} β Match a SSN
[a-z]\w{1,7} β Match a UW NetID
* + {n,}greedy β Match as much as possible
<.+> β Finds 1 big match in <b>bold</b>
*? +? {n,}?lazy β Match as little as possible
<.+?> β Finds 2 matches in <b>bold</b>
\b β "Word" edge (next to non "word" character)
\bring β Word starts with "ring", ex ringtone
ring\b β Word ends with "ring", ex spring
\b9\b β Match single digit 9, not 19, 91, 99, etc..
\b[a-zA-Z]{6}\b β Match 6-letter words
\B β Not word edge
\Bring\B β Match springs and wringer
^\d*$ β Entire string must be digits
^[a-zA-Z]{4,20}$ β String must have 4-20 letters
^[A-Z] β String must begin with capital letter
[\.!?"')]$ β String must end with terminal puncutation
(?i)[a-z]*(?-i) β Ignore case ON / OFF
(?s).*(?-s) β Match multiple lines (causes . to match newline)
(?m)^.*;$(?-m) β ^ & $ match lines not whole string
(?x) β #free-spacing mode, this EOL comment ignored
(?-x) β free-spacing mode OFF
/regex/ismx β Modify mode for entire string
(in\|out)put β Match input or output
\d{5}(-\d{4})? β US zip code ("+ 4" optional)
Parser tries EACH alternative if match fails after group. Can lead to catastrophic backtracking.
(to) (be) or not \1 \2 β Match to be or not to be
([^\s])\1{2} β Match non-space, then same twice more Β aaa, ...
\b(\w+)\s+\1\b β Match doubled words
on(?:click\|load) β Faster than: on(click\|load)
Use non-capturing or atomic groups when possible
(?>red\|green\|blue) β Faster than non-capturing
(?>id\|identity)\b β Match id, but not identity
"id" matches, but \b fails after atomic group, parser doesn't backtrack into group to retry 'identity' If alternatives overlap, order longer to shorter.
(?= ) β 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
\b\w+?(?=ing\b) β Match warbling, string, fishing, ...
\b(?!\w+ing\b)\w+\b β Words NOT ending in "ing"
(?<=\bpre).*?\b β Match pretend, present, prefix, ...
\b\w{3}(?<!pre)\w*?\b β Words NOT starting with "pre"
\b\w+(?<!ing)\b β Match words NOT ending in "ing"
Match "Mr." or "Ms." if word "her" is later in string
M(?(?=.*?\bher\b)s|r)\.
requires lookaround for IF condition
Import the regular expressions module
import re
>>> 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(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']
>>> 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(r'\d+', 'Sample123string42with777numbers')
['Sample', 'string', 'with', 'numbers']
>>> ip_lines = "catapults\nconcatenate\ncat"
>>> print(re.sub(r'^', r'* ', ip_lines, flags=re.M))
* catapults
* concatenate
* cat
>>> 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
re.findall β Returns a list containing all matches
re.finditer β Return an iterable of match objects (one for each match)
re.search β Returns a Match object if there is a match anywhere in the string
re.split β Returns a list where the string has been split at each match
re.sub β Replaces one or many matches with a string
re.compile β Compile a regular expression pattern for later use
re.escape β Return string with all non-alphanumerics backslashed
re.I β re.IGNORECASE β Ignore case
re.M β re.MULTILINE β Multiline
re.L β re.LOCALE β Make \w,\b,\s locale dependent
re.S β re.DOTALL β Dot matches all (including newline)
re.U β re.UNICODE β Make \w,\b,\d,\s unicode dependent
re.X β re.VERBOSE β Readable style
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));
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));
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);
let text = 'Here are apples and apPleS';
let regex = /apples/gi;
// Output: [ "apples", "apPleS" ]
console.log(text.match(regex));
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))
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]);
let text = 'Do you like aPPles?';
let regex = /apples/i
// Output: Do you like mangoes?
let result = text.replace(regex, 'mangoes');
console.log(result);
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);
preg_match() β Performs a regex match
preg_match_all() β Perform a global regular expression match
preg_replace_callback() β Perform a regular expression search and replace using a callback
preg_replace() β Perform a regular expression search and replace
preg_split() β Splits a string by regex pattern
preg_grep() β Returns array entries that match a pattern
$str = "Visit Microsoft!";
$regex = "/microsoft/i";
// Output: Visit QuickRef!
echo preg_replace($regex, "QuickRef", $str);
$str = "Visit QuickRef";
$regex = "#quickref#i";
// Output: 1
echo preg_match($regex, $str);
$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]);
}
$arr = ["Jane", "jane", "Joan", "JANE"];
$regex = "/Jane/";
// Output: Jane
echo preg_grep($regex, $arr);
$str = "Jane\tKate\nLucy Marion";
$regex = "@\s@";
// Output: Array("Jane", "Kate", "Lucy", "Marion")
print_r(preg_split($regex, $str));
Pattern p = Pattern.compile(".s", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("aS");
boolean s1 = m.matches();
System.out.println(s1); // Outputs: true
boolean s2 = Pattern.compile("[0-9]+").matcher("123").matches();
System.out.println(s2); // Outputs: true
boolean s3 = Pattern.matches(".s", "XXXX");
System.out.println(s3); // Outputs: false
CANON_EQ β Canonical equivalence
CASE_INSENSITIVE β Case-insensitive matching
COMMENTS β Permits whitespace and comments
DOTALL β Dotall mode
MULTILINE β Multiline mode
UNICODE_CASE β Unicode-aware case folding
UNIX_LINES β Unix lines mode
Pattern compile(String regex [, int flags]) boolean matches([String regex, ] CharSequence input) String[] split(String regex [, int limit]) String quote(String s)
int start([int group | String name]) int end([int group | String name]) boolean find([int start]) String group([int group | String name]) Matcher reset()
boolean matches(String regex) String replaceAll(String regex, String replacement) String[] split(String regex[, int limit])
There are more methods ...
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);
REGEXP β Whether string matches regex
REGEXP_INSTR() β Starting index of substring matching regex (NOTE: Only MySQL 8.0+)
REGEXP_LIKE() β Whether string matches regex (NOTE: Only MySQL 8.0+)
REGEXP_REPLACE() β Replace substrings matching regex (NOTE: Only MySQL 8.0+)
REGEXP_SUBSTR() β Return substring matching regex (NOTE: Only MySQL 8.0+)
expr REGEXP pat
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(expr, pat, repl[, pos[, occurrence[, match_type]]])
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(expr, pat[, pos[, occurrence[, match_type]]])
mysql> SELECT REGEXP_SUBSTR('abc def ghi', '[a-z]+');
abc
mysql> SELECT REGEXP_SUBSTR('abc def ghi', '[a-z]+', 1, 3);
ghi
REGEXP_LIKE(expr, pat[, match_type])
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(expr, pat[, pos[, occurrence[, return_option[, match_type]]]])
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