Detailed Explanation of JavaScript Regular Expressions

  • 2021-12-04 17:59:49
  • OfStack

Catalog 1. Regular Expression Creation 2. Use Pattern 2.1 Use Simple Pattern 2.2 Use Special Character 3. Apply 3.1 Split String 3.2 Grouping 3.3 Greedy Match3.4 Regular Expression Flag 3.5 test () Method 4. Common Regular (Reference) Summary

1. Regular expression creation

JavaScript has two ways to create regular expressions:

Type 1: Directly through/regular expression/write Type 2: Create an RegExp object with new RegExp ('Regular Expression')

const re1 = /ABC\-001/;
const re2 = new RegExp('ABC\\-001');
re1; // /ABC\-001/
re2; // /ABC\-001/

Note that if the second way is used, the two\ of the string is actually one\ because of the escape problem of the string.

2. Usage patterns

2.1 Using Simple Mode

Simple patterns are made up of direct matches found. For example, the/abc/pattern matches that only the character 'abc' occurs simultaneously and in this order in a string. In "Hi, do you know your abc 's? "And" The latest airplane designs evolved from slabcraft. "will match successfully. In the above two examples, the matching is the substring 'abc'. Will not be matched in the string "Grab crab" because it does not contain any 'abc' substring.

2.2 Use of Special Characters

For example: Pattern/abc/matches a single 'a' followed by zero or more 'b' (meaning zero or more of the preceding item), followed by any combination of characters of 'c'. In the string "s 'scbbabbbbcdebc", this pattern matches the substring "abbbbc".

字符 含义
\ 匹配将依照下列规则:
在非特殊字符之前的反斜杠表示下1个字符是特殊的,不能从字面上解释。例如,前面没有''的'd'通常匹配小写'd'。如果加了'',这个字符变成了1个特殊意义的字符,意思是匹配1个数字。
反斜杠也可以将其后的特殊字符,转义为字面量。例如,模式 /a/ 代表会匹配 0 个或者多个 a。相反,模式 /a*/ 将 '' 的特殊性移除,从而可以匹配像 "a*" 这样的字符串。
使用 new RegExp("pattern") 的时候也不要忘记将 \ 进行转义,因为 \ 在字符串里面也是1个转义字符。
^ 匹配输入的开始,例如,/^A/ 并不会匹配 "an A" 中的 'A',但是会匹配 "An E" 中的 'A'。
$ 匹配输入的结束。例如,/t$/ 并不会匹配 "eater" 中的 't',但是会匹配 "eat" 中的 't'。
* 匹配前1个表达式0次或多次。等价于 {0,}。例如,/bo*/会匹配 "A ghost boooooed" 中的 'booooo'
+ 匹配前面1个表达式1次或者多次。等价于 {1,}。例如,/a+/匹配了在 "candy" 中的 'a',和在 "caaaaaaandy" 中所有的 'a'。
? 匹配前面1个表达式0次或者1次。等价于 {0,1}。例如,/e?le?/ 匹配 "angel" 中的 'el',和 "angle" 中的 'le' 以及"oslo' 中的'l'。
如果紧跟在任何量词 *、 +、? 或 {} 的后面,将会使量词变为非贪婪的(匹配尽量少的字符),和缺省使用的贪婪模式(匹配尽可能多的字符)正好相反。
例如,对 "123abc" 应用 /\d+/ 将会返回 "123",如果使用 /\d+?/,那么就只会匹配到 "1"。
. 匹配除换行符之外的任何单个字符。例如,/.n/将会匹配 "nay, an apple is on the tree" 中的 'an' 和 'on',但是不会匹配 'nay'。
x y
{n} n是1个正整数,匹配了前面1个字符刚好发生了n次。
比如,/a{2}/不会匹配“candy”中的'a',但是会匹配“caandy”中所有的a,以及“caaandy”中的前两个'a'。
{n,m} n 和 m 都是整数。匹配前面的字符至少n次,最多m次。如果 n 或者 m 的值是0, 这个值被忽略。例如,/a{1, 3}/ 并不匹配“cndy”中的任意字符,匹配“candy”中的a,匹配“caandy”中的前两个a,也匹配“caaaaaaandy”中的前3个a。注意,当匹配”caaaaaaandy“时,匹配的值是“aaa”,即使原始的字符串中有更多的a。
[xyz] 1个字符集合。匹配方括号中的任意字符,包括转义序列。你可以使用破折号(-)来指定1个字符范围。对于点(.)和星号(*)这样的特殊符号在1个字符集中没有特殊的意义。他们不必进行转义,不过转义也是起作用的。
例如,[abcd] 和[a-d]是1样的。他们都匹配"brisket"中的‘b',也都匹配“city”中的‘c'。/[a-z.]+/ 和/[\w.]+/与字符串“test.i.ng”匹配。
[^xyz] 1个反向字符集。也就是说, 它匹配任何没有包含在方括号中的字符。你可以使用破折号(-)来指定1个字符范围。任何普通字符在这里都是起作用的。
\b 匹配1个词的边界。1个词的边界就是1个词不被另外1个“字”字符跟随的位置或者没有其他“字”字符在其前面的位置。注意,1个匹配的词的边界并不包含在匹配的内容中。换句话说,1个匹配的词的边界的内容的长度是0。例如:
/\bm/匹配“moon”中的‘m';/oo\b/并不匹配"moon"中的'oo',因为'oo'被1个“字”字符'n'紧跟着。/oon\b/匹配"moon"中的'oon',因为'oon'是这个字符串的结束部分。这样他没有被1个“字”字符紧跟着。
\d 匹配1个数字。等价于[0-9]。例如, /\d/ 或者 /[0-9]/ 匹配"B2 is the suite number."中的'2'。
\D 匹配1个非数字字符。等价于[^0-9]。例如, /\D/ 或者 /[^0-9]/ 匹配"B2 is the suite number."中的'B' 。
\f 匹配1个换页符 (U+000C)。
\n 匹配1个换行符 (U+000A)。
\r 匹配1个回车符 (U+000D)。
\s 匹配1个空白字符,包括空格、制表符、换页符和换行符。等价于[ \f\n\r\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]。
例如, /\s\w*/ 匹配"foo bar."中的' bar'。
\S 匹配1个非空白字符。等价于[^ \f\n\r\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]。
例如, /\S\w*/ 匹配"foo bar."中的'foo'。
\t 匹配1个水平制表符 (U+0009)。
\w 匹配1个单字字符(字母、数字或者下划线)。等价于[A-Za-z0-9_]。
例如, /\w/ 匹配 "apple," 中的 'a',"$5.28,"中的 '5' 和 "3D." 中的 '3'。
\W 匹配1个非单字字符。
\n 在正则表达式中,它返回最后的第n个子捕获匹配的子字符串(捕获的数目以左括号计数)。

3. Application

3.1 Split String

Splitting strings with regular expressions is more flexible than using fixed characters. Common splitting codes:


'a d   c'.split(' '); // ['a', 'd', '', '', 'c']

The above method can't recognize continuous spaces, so use regular expressions instead:


'a b   c'.split(/\s+/); // ['a', 'b', 'c']

No matter how many spaces can be split normally. Add ',':


'a,b, c  d'.split(/[\s\,]+/); // ['a', 'b', 'c', 'd']

Re-join; :


'a,b;; c  d'.split(/[\s\,\;]+/); // ['a', 'b', 'c', 'd']

Therefore, regular expressions can be used to convert irregular input into correct arrays.

3.2 Grouping

In addition to judging a match, a regular expression can also extract a substring, and () is the packet to be extracted (Group). For example:

^ (\ d {4})-(\ d {4, 9}) $defines two groups to extract the area code and local number directly from the matching string:


var re = /^(\d{4})-(\d{4,9})$/;
re.exec('0530-12306'); // ['010-12345', '010', '12345']
re.exec('0530 12306'); // null

The exec () method returns an array after a successful match, with the first element being the entire string to which the regular expression matches, followed by strings representing the successfully matched substring.

The exec () method returns null when a match fails.

3.3 Greedy Matching

Note that regular matching defaults to greedy matching, that is, matching as many characters as possible. As follows, match the 0 after the number:


var re = /^(\d+)(0*)$/;
re.exec('102300'); // ['102300', '102300', '']

Because\ d + uses greedy matching, it directly matches all the following zeros, and the result 0* can only match empty strings.

You must make\ d + use non-greedy matching (that is, match as little as possible) in order to match the following 0 and add a? You can make\ d + use non-greedy matching:


var re = /^(\d+?)(0*)$/;
re.exec('102300'); // ['102300', '1023', '00']

3.4 Regular expression flags


g	 Global search. 
i	 Case-insensitive search. 
m	 Multi-line search. 
y	 Perform a "sticky" search , Matching starts at the current position of the target string, and you can use the y Signs. 

3.5 test () Method

The test () method detects whether a string matches a pattern, and returns true if the string contains matching text, or false if not.


var re = /^(\d{4})-(\d{4,9})$/;
re.test('0530-12321'); // true
re.test('0530-123ab'); // false
re.test('0530 12321'); // false

4. Common regularities (reference)


'a d   c'.split(' '); // ['a', 'd', '', '', 'c']
0

Summarize

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: