Regular Expressions
Test Method
.test()
- takes regular expression (regex), applies it to a string (which is placed inside the parenthesis) & returns true or false depending if the pattern is found or not
Example:
Multiple Patterns
use
alternation
orOR
operator:|
(pipe)matches pattern before and after it
Example:
/yes | no/
Ignore Case
use "i" flag
Example:
/ignore case/i
will match this pattern regardless if any is capitalized or not
Extract Matches
.match()
- extract the actual matchapply the method on a string and pass in the regex pattern inside the parenthesis
Example:
Find more than the first match
use "g" flag
Example:
Match anything with wildcard period
the wildcard "." will match any one character
Example:
Match single character with multiple possibilities
search for a literal pattern with character classes
character classes allow you to define a group of characters
place them inside
[]
Example:
want to match beg, bug, big but not bog
Regex: /b[eiu]g/
Match everything but letters and numbers
include letters and numbers:
/[A-Za-z0-9]/
equivalent to
\w
:/\w/
exclude letters and numbers:
/[^A-Za-z0-9]/
equivalent to
\W
:/\W/
Example:
useful for when you want to search ahead for multiple patterns
positive look ahead: (?=...)
negative look ahead: (?!...)
?
: possible existence of previous character if exact number
Match all numbers
character class: /[0-9]/
or shorthand \d
: /\d/
Match all non-numbers
character class: /[^0-9]/
or shorthand \D
: /\D/
Restrict possible user names
can only use alpha-numeric characters
can not begin with numbers and must only be at the end ( can ne zero or more at the end only)
letters can by upper or lower case
use name must be at least two characters long and if only two characters, must be alpha characters only (no numbers)
Examples:
s1: /^[a-z][a-z]+\d*\S|^[a-z]\d\d+\S/i
s2: /^[a-z]([0-9]{2,}|[a-z+\d*)\S]/i
{2,}
: ends with two or more numbers{3, 5}
: between 3 and 5 times{}
: quantity specifiers+
: 1 or more characters*
: 0 or more characters\S
: non-white spacescharacter class:
[^/r/t/f/n/v]
Match whitespace
s = space
r = carriage return
t = tab
f = form feed
n = new line
v = vertical tab