RegExp Flashcards
Attributes
Reference data type Has methods & properties #safe
Instantiation
// literal /regex/g // constructor new RegExp("regex", "g");
Properties
.global - whether to test for all matches or just the first—set via flag. #safe #read-only
.ignoreCase - case insensitive—set via flag. #safe #read-only
.lastIndex - the index at which to start the next match #safe #read-or-write
.multiline - whether the pattern should match every line—set via flag. #safe #read-only
.source - text of the pattern #safe #read-only
Methods
.exec —searches string for a pattern match and return detail results
.test —test if pattern matches string
.toString —returns string representation of the RegExp that looks like the literal instantiation syntax: /r/g
Flags
g - global searches (meaning don’t stop at first occurrence)
i - ignore case / case insensitive
m - apply begin and end characters (^ and $) to every line in a multi line string
String methods that accept regexp as arguments
String.prototype... .match() .replace() .search() .split()
Match beginning or/and end of string
^ beginning
$ end
Matches a certain number of times (6)
* match 0+ times ? match 0-1 times \+ match 1+ times {n} match n times {n,} match n+ times {n,m} match n-m times (inclusive)
Matching is based on the previous character, like:
/\s+/ - match whitespace 1+ times
/ap*/ - match “p” 0+ times
/[a-z]?/ - match lowercase letter 0-1 times
Character matching (3)
. matches any character except a newline
[…] matches any characters inside
[^…] matches any characters NOT inside
Examples:
/a[pl]+/ matches “app”, “all”, “alp” etc.
Special characters for matching (10)
\b word boundary, like /\bno/ matches the first “no” in “nono”
\B not word boundary, /\Bno/ matches second “no”
\d number, /\d{3}/ matches “123”
\D not number /\D{1}/ matches “s” but not “1”
\w word character - letter, number, underscore
\W not word character - anything but letter, number, underscore
\s single whitespace character - space, tag, newline, etc.
\S not whitespace character
\t tab
\n newline
Capturing parens & Non-capturing parens.
What methods can use capturing parens?
Capturing parenthesis: meaning it will remember the match
(…)
Non-capturing parens: won’t remember, but useful for grouping things together, like:
(?:foo){1,2} -> {1,2} is applied to the entire word “foo”, not just the precending single-character like normal
foo{1,2} -> only applies to last “o”
Capturing parens can be used by:
String.prototype.replace
RegExp.prototype.exec
Operators: Or
Or: |
/a|b/ -> a or b
Lookahead & Negated Lookahead
Lookahead lets you match things if they are followed by something else:
x(?=y) -> matches x if followed by y
/Jack(?=Black|Frost)/ -> matches Jack if followed by Black or Frost, but neither Black nor Frost are part of the match
Negated lookahead let’s you match things if not followed by something else:
x(?!y)
/\d+(?!.)/.exec(“3.141”) -> matches “141”