JS笔记:正则表达式 (Regex)

Regex Usage

RegEx methods

exec
Search for match in string; returns array or null. The return value array only contains the first capture and match. It's meant to be used with a while loop.

Usage:

// without capture group
var re = /cat/g;
var result = re.exec("cats are cats");
console.log(result); //  [ 'cat', index: 0, input: 'cats are cats' ]
result = re.exec("dogs are dogs");
console.log(result); // null

// includes capture group
var re = /(cat)/g;
var result = re.exec("cats are cats");
console.log(result); //  [ 'cat', 'cat', index: 0, input: 'cats are cats' ]

var re = /(cat)s/g;
var result = re.exec("cats are cats");
console.log(result); //  [ 'cats', 'cat', index: 0, input: 'cats are cats' ]

test - tests for a match in a string, returns true if a match exists.

String methods

Note: match and replace does not return / consider capture groups. They only return matches but not captures.

match
Same as exec, except used on a string, ignores capture groups, returns an array with all matches, not to be used with while loop.
Usage:

var re = /cat/g;
var result = "cats are cats".match(re);
console.log(result); //  [ 'cat', 'cat' ]
result = re.exec("dogs are dogs");
console.log(result); // null

replace
Searches for a match in a string, and replaces the matched substring with a replacement substring.
Inputs:

  • $& - Inserts the matched substring.
  • $` - Inserts the portion of the string that precedes the matched substring.
  • $' - Inserts the portion of the string that follows the matched substring.

Regex Flags

g - global, match all
i - ignore case
m - multiline
如:

var re = /a/gim;
var re = new RegExp("\"(?:\\.|[^\\\\\\\"])*\"", 'g');

Regex Groups

Capturing group: (x)

Non-capturing group: (?:x)

Regex Classes

Character class: [...]
[A-Za-z]

Digit character: \d
[0-9]

Non-digit character: \D
[^0-9]

Alphanumeric: \w
[A-Za-z0-9]

Quantifier: {}
/w{3}/相当于match w 3 times (i.e. www).

Common Usage Examples

Parse URLs

Escape all quotes

Retrieve data from a specifically formatted string

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

你可能感兴趣的:(JS笔记:正则表达式 (Regex))