Talking about JS regular RegExp object

  • 2021-11-29 22:51:17
  • OfStack

Directory 1, RegExp Object 2, Syntax 2.1 Definitions 2.2 Modifiers 2.3 Square Brackets 2.4 Metacharacters 2.5 Quantifiers 2.6 Methods

1. RegExp Object

Regular expressions are objects that describe character patterns. Regular expressions are used for pattern matching and retrieval substitution of strings, and are powerful tools for pattern matching of strings. Reference: w3cschool JavaScript RegExp Object

2. Grammar

2.1 Definition

When using constructors to create regular objects, you need regular character escape rules (preceded by a backslash\)


/*  For example, the following two definitions are equivalent  */

//  Constructor mode 
const reg = new RegExp("\\w+");
//  Literal method 
const reg = /\w+/;

2.2 modifiers

Used to perform case-sensitive and global matching

修饰符 描述
i 执行对大小写不敏感的匹配。
g 执行全局匹配(查找所有匹配而非在找到第1个匹配后停止)。
m 执行多行匹配。


    /*  Chestnut  */
const reg = /\w/gi

2.3 Square brackets

Used to find characters in a range:

表达式 描述
[abc] 查找方括号之间的任何字符。
[^abc] 查找任何不在方括号之间的字符。
[0-9] 查找任何从 0 至 9 的数字。
[a-z] 查找任何从小写 a 到小写 z 的字符。
[A-Z] 查找任何从大写 A 到大写 Z 的字符。
[A-z] 查找任何从大写 A 到小写 z 的字符。
[adgk] 查找给定集合内的任何字符。
[^adgk] 查找给定集合外的任何字符。
(red|blue|green) 查找任何指定的选项。


/*  Chestnut  */
const reg = /[0-9]/g

2.4 metacharacter

Is a character with a special meaning:

元字符 描述
. 查找单个字符,除了换行和行结束符。
\w 查找单词字符。
\W 查找非单词字符。
\d 查找数字。
\D 查找非数字字符。
\s 查找空白字符。
\S 查找非空白字符。
\b 匹配单词边界。
\B 匹配非单词边界。
\0 查找 NUL 字符。
\n 查找换行符。
\f 查找换页符。
\r 查找回车符。
\t 查找制表符。
\v 查找垂直制表符。
\xxx 查找以8进制数 xxx 规定的字符。
\xdd 查找以106进制数 dd 规定的字符。
\uxxxx 查找以106进制数 xxxx 规定的 Unicode 字符。


/*  Chestnut  */
const reg = /\d/g   //  Matching digits 

2.5 Quantifiers

Is a character with a special meaning:

量词 描述
n+ 匹配任何包含至少1个 n 的字符串。
n* 匹配任何包含零个或多个 n 的字符串。
n? 匹配任何包含零个或1个 n 的字符串。
n{X} 匹配包含 X 个 n 的序列的字符串。
n{X,Y} 匹配包含 X 至 Y 个 n 的序列的字符串。
n{X,} 匹配包含至少 X 个 n 的序列的字符串。
n$ 匹配任何结尾为 n 的字符串。
^n 匹配任何开头为 n 的字符串。
?=n 匹配任何其后紧接指定字符串 n 的字符串。
?!n 匹配任何其后没有紧接指定字符串 n 的字符串。


/*  Chestnut  */
const reg = /\d+/g  //  Matching at least 1 Number 

2.6 Methods

Is a character with a special meaning:

方法 描述 FF IE
compile 编译正则表达式。 1 4
exec 检索字符串中指定的值。返回找到的值,并确定其位置。 1 4
test 检索字符串中指定的值。返回 true 或 false。 1 4

方法 描述 FF IE
search 检索与正则表达式相匹配的值。 1 4
match 找到1个或多个正则表达式的匹配。 1 4
replace 替换与正则表达式匹配的子串。 1 4
split 把字符串分割为字符串数组。 1 4


/*  Chestnut  */
var patt = /Hello/g
var result = patt.test(str) //  Find Hello String  -> true


Related articles: