正则表达式

2022-06-06 10:39阅读 99

[ABC] 匹配括号中字符,

const str = 'hello, 2019'
str.match(/[hello]/g) // ['h', 'e', 'l', 'l', 'o']
str.match(/[helo]/g) // ['h', 'e', 'l', 'l', 'o']
str.match(/[abcde123]/g) // ['e', '2', '1']

[A-Z] 区间匹配,匹配从A到Z 26个大写

const str = 'Hello, 2019'
str.match(/[A-Z]/g) // ['H']

[a-z] 匹配从a到z 26个小写

const str = 'Hello, 2019'
str.match(/[a-z]/g) // ['e','l', 'l', 'o' ]

[A-z] 匹配a-z和A-Z ,共52个大小写

const str = 'Hello, 2019'
str.match(/[A-z]/g) // ['H', 'e','l', 'l', 'o' ]

[a-Z] 错误的区间 Range out of order in character class

[A-Za-z0-9] 多个区间匹配,

const str = 'Hello, 2019'
str.match(/[A-Za-z0-9]/g) // ['H', 'e','l', 'l', 'o', '2', '0', '1', '9' ]

[^ABC] 匹配除括号以外的字符,

const str = 'hello, 2019'
str.match(/[^hello]/g) // [',', ' ', '2', '0', '1', '9']

str.match(/[^abcde123]/g) // ['h', 'l', 'l', 'o', ',', ' ', '0', '9']

修饰符

+ 修饰符前面的字符出现次数 >=1,等价于 {1,}

* 修饰符前面的字符出现次数 >=0,等价于 {0,}

? 修饰符前面的字符出现次数 <=1,等价于 {0,1}(非贪婪限定符)

. 匹配任意字符

^

$

{n} 字符出现的次数

{n,m} 字符出现的次数区间

非打印字符

\d匹配数字

\D匹配非数字

\s匹配空格和换行

\S匹配非空格和非换行

\w匹配单字字符(数字、字母、下划线)

\W匹配非单字字符

\ 转义字符

\f匹配换页

\r匹配回车

\n匹配换行

\t匹配水平制表符

\v匹配垂直制表符

\ \

标签
标签
标签