Tips: 字串方法match()回傳根據正則運算式匹配到的結果
1. 常用符號/鏈接標志
1.1 開頭結尾標志
^以...開頭$以...結尾
const reg1 = /^\d/ // 以數字開頭
const reg2 = /^[a-z]/ // 以小寫字母開頭
const reg3 = /\d$/ // 以數字結尾
const reg4 = /[a-z]$/ // 以小寫字母結尾
const str = '123abc'
str.match(reg1) // '1'
str.match(reg2) // ''
str.match(reg3) // ''
str.match(reg4) // 'c'
1.2 多次匹配(限定符)
+號,匹配前面的字符1 ~ n次*號,匹配前面的字符0 ~ n次?號,匹配前面的字符0 ~ 1次{n,},匹配前面的字符至少n次{n,m},匹配前面的字符n ~ m次
const reg1 = /\d/ // 匹配單個數字
const reg2 = /\d+/ // 匹配1~n個數字
const reg3 = /\d*/ // 匹配0~n個數字
const reg4 = /\d?/ // 匹配0~1個數字
const reg5 = /\d{2,}/g // 匹配至少2個數字(g全域匹配)
const reg6 = /\d{3,6}/g // 匹配3~6個數字
const str = '12345678abc98def7'
str.match(reg1) // '1'
str.match(reg2) // '12345678'
str.match(reg3) // '12345678'
str.match(reg4) // '1'
str.match(reg5) // ['12345678', '98']
str.match(reg6) // '123456'
2. 字符
2.1 普通字符
[abc]匹配[]中的所有字符[^abc]匹配除去[^]中的所有字符[A-Z]匹配某個區間的所有字符.匹配除去換行符(\n、\r)的所有字符\w匹配字母、數字、下劃線,等價于[A-Za-z0-9_]
const reg1 = /[ame]{3}/ // 匹配ame三個字符
const reg2 = /[^N]+/ // 匹配除去N的所有字符
const reg3 = /[a-z]+/ // 匹配a-z這個區間的所有字符
const reg4 = /.+/ // 匹配除去換行符(\n、\r)的所有字符
const reg5 = /\w{3,6}/ // 匹配字母、數字、下劃線,3 ~ 6個字符
const str = 'Name1-2_3'
str.match(reg1) // 'ame'
str.match(reg2) // 'ame1-2_3'
str.match(reg3) // 'ame'
str.match(reg4) // 'Name1-2_3'
str.match(reg5) // 'Name1'
2.2 非列印字符
\d,匹配一個數字\n,匹配一個換行符\s,匹配任何空白字符\S,匹配任何非空白字符
3. 修飾符
- 修飾符(flags)用于指定額外的匹配策略,
- 語法:
/pattern/flags
3.1 常用修飾符
i,ignore不區分大小寫g,global全域匹配m,multi line多行匹配
const reg1 = /[a-z]+/i // 匹配字母,不區分大小寫
const reg2 = /[A-Z]+/ // 匹配大寫字母
const reg3 = /[A-Z]+/g // 匹配大寫字母,且全域
const str = 'AncientChina'
str.match(reg1) // 'AncientChina'
str.match(reg2) // 'A'
str.match(reg3) // ['A', 'C']
參考
https://www.runoob.com/regexp 菜鳥教程
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/552545.html
標籤:JavaScript
下一篇:返回列表
