I’ve been writing some regex lately and compiled this handy little cheat sheet.
Start the expression: /^
Space: [\s] or \s
Parentheses: [(] and [)]
Optional flag: put a ‘?’ after the phrase Hyphen (first or last character): - or [-]
Hyphen (not first or last character): \-
If you want options in a slot, put brackets around the options: [-.\s]
= hyphen, period, or space required.
If you want options to be optional, add a question mark: [-.\s]?
= optional slot, but a hyphen, period, or space required Number: \d
Quantifier: {3}
(exactly 3)
1 or more: +
n or more: {2,} (2 or more)
0 or 1: ?
0 or 1 digit: \d?
1 or more digits: \d+
String: ^
String of length n: ^{n} (where 'n' is a number)
Quantified Number: \d{3} (exactly 3 numbers)
Literal: \ ([\@] would be a required 'at' sign)
1 digit number, in a range: [n-n] ([0-9] is a required single digit number ranging from 0-9)
(\+|1\s)?
accepts a plus sign or (the pipe character is “or”) a 1 followed by a space and makes it optional.
End the expression: $/
Common Regex Phrases:
US Phone Number (123)456-7890: /^[(][2-9]\d{2}[)][2-9]\d{2}[-]\d{4}$/
(I’ll add more here as time progresses)
Hope this helps, I’ll be using it for sure.