Easy-to-understand regular expressions for beginners

background

In fact, before using regular expressions, we have used symbols similar to regular expressions when looking for files, for example:

// 匹配多个任意字符
ls *.js
// 只匹配一个任意字符
ls ?.js

This method is useful but limited, while regular expressions are more complete and powerful.

simple example

"0123abc".match(/^[0-9]+abc$/)   // 0123abc
  • ^ matches the beginning of the input string.
  • [0-9]+ matches multiple digits, [0-9] matches a single digit, + matches one or more digits.
  • abc$ matches the letter abc and ends with abc, and $ matches the end position of the input string.

In js, we can not only use match, but here are some functions related to regular expressions: js: summary of common methods of regular expressions test, exec, match, matchAll, replace, replaceAll, search

grammar

all special symbols

// 匹配除换行符(\n、\r)之外的任何单个字符,相等于 [^\n\r]。
.
// 匹配所有。\s 是匹配所有空白符,包括换行,\S 非空白符,不包括换行。[\s\S]
\s\S
// 匹配字母、数字、下划线。等价于 [A-Za-z0-9_],[\w]
\w
// 捕获组,获取一个匹配的元素,使用 match、exec 等函数可以拿到
()
// 匹配前面的子表达式零次或多次。
*
// 匹配前面的子表达式1次或多次。
+
// 匹配前面的子表达式0次或1次。
?
// 转义
\
// 正则的开始和结尾(可以省略),如果^在[]中使用代表非
^$
// 标记限定符表达式
{
    
    
// 中括号表达式
[
// 或
|

normal characters

matches characters containing hwl

// ['h', 'l', 'l', 'w', 'l']
"hello world".match(/[hwl]/g)

matches characters that do not contain hwl

// ['e', 'o', ' ', 'o', 'r', 'd']
"hello world".match(/[^hwl]/g)

Configure alphanumeric

[a-z]
[A-Z]
[a-zA-Z0-9]
[a-zA-Z0-9_]

qualifier

// 匹配前面的子表达式零次或多次。
*
// 匹配前面的子表达式1次或多次。
+
// 匹配前面的子表达式0次或1次。
?
// 标记限定符表达式
{
    
    n}
{
    
    n,}
{
    
    n,m}

Example:

// 第一个数字为1-9,后面的数字为0-9
/[1-9][0-9]*/

*+It is greedy, it will match as much text as possible, only adding a after them ?can achieve the minimum match, for example:
want to match the entire text containing h1.

// 贪婪
"<h1>hello world</h1>".match(/<.*>/g)
// 非贪婪
"<h1>hello world</h1>".match(/<.*?>/g)

insert image description here
Using greedy will match the last eligible element as much as possible, so .the last >element that satisfies and ends with is matched, and the nearest one is taken when using non-greedy.

selector

()

This is in js: a summary of common methods of regular expressions test, exec, match, matchAll, replace, replaceAll, search has detailed examples.

Modifier

// 不区分大小写
i
// 全局匹配
g
// 使边界字符 ^ 和 $ 匹配每一行的开头和结尾,记住是多行,而不是整个字符串的开头和结尾。
m
// 默认情况下的圆点 . 是匹配除换行符 \n 之外的任何字符,加上 s 修饰符之后, . 中包含换行符 \n。
s

example

Commonly used regular summary

Supongo que te gusta

Origin blog.csdn.net/weixin_43972437/article/details/130706129
Recomendado
Clasificación