JS 正则表达式及部分示例


一、RegExp 对象常用方法

方法描述
test检索字符串中指定的值。返回 true 或 false。

二、支持正则表达式的 String 对象的常用方法

方法描述
search检索与正则表达式相匹配的值。
match找到一个或多个正则表达式的匹配。
replace替换与正则表达式匹配的子串。

三、正则表达式

1. 匹配任意字符

使用通配符.作为任何字符的占位符

const testRegex = /.ui/gi,
  testString = "Cuiht CUIHT cuiht";
console.log(testString.match(testRegex));// ["Cui", "CUI", "cui"]
2. 匹配字母

使用字符集内的范围[a-z]

const testRegex = /[a-z]ui/gi,
  testRegex_ab = /[ab]ui/gi,
  testString = "Cuiht CUIHT cuiht";
console.log(testString.match(testRegex));// ["Cui", "CUI", "cui"]
console.log(testString.match(testRegex_ab));// null
3. 匹配数字

使用字符集内的范围[0-9],匹配所有数字[0-9]简写\d,匹配所有非数字\D

const testRegex = /[0-3]cht/g,
  testRegex_Number = /\d/g,
  testRegex_notNumber = /\D/g,
  testString = "1cht 2cht 3cht 4cht 5cht";
console.log(testString.match(testRegex)); // ["1cht", "2cht", "3cht"]
console.log(testString.match(testRegex_Number)); // ["1", "2", "3", "4", "5"]
console.log(testString.match(testRegex_notNumber)); // ["c", "h", "t", " ", "c", "h", "t", " ", "c", "h", "t", " ", "c", "h", "t", " ", "c", "h", "t"]
4. 匹配所有字母及数字

匹配所有字母及数字使用\word简写\w,匹配所有非字母及数字\W

const testRegex = /\wcht/g,
  testRegex_Word = /\w/g,
  testRegex_notWord = /\W/g,
  testString = "1cht 2cht 3cht";
console.log(testString.match(testRegex)); // ["1cht", "2cht", "3cht"]
console.log(testString.match(testRegex_Word)); // ["1", "c", "h", "t", "2", "c", "h", "t", "3", "c", "h", "t"]
console.log(testString.match(testRegex_notWord)); // [" ", " "]
5. 匹配中文
const testRegex = /[\u4e00-\u9fa5]/g,
  testString = "测试123 2cht 3cht";
console.log(testString.match(testRegex)); // ["测", "试"]
6. 匹配空格

匹配空格和回车符使用\s,匹配非空格和回车符\S

const testRegex_S = /\s/g,
  testRegex_notS = /\S/g,
  testString = "1cht 2cht 3cht";
console.log(testString.match(testRegex_S)); // [" ", " "]
console.log(testString.match(testRegex_notS)); // ["1", "c", "h", "t", "2", "c", "h", "t", "3", "c", "h", "t"]
7.匹配多个模式

使用操作符号|

const testRegex = /yes|no|maybe/,
  testString = "yes",
  testString1 = "yo";
console.log(testRegex.test(testString)); // true
console.log(testRegex.test(testString1)); // false
8.提取变量
const testRegex_i = /Cuiht/i,
  testRegex_g_i = /Cuiht/gi;
testString = "Cuiht CUIHT cuiht";
// 提取第一个不区分大小写匹配项
console.log(testString.match(testRegex_i));// ["Cuiht"]
// 提取所有不区分大小写匹配项
console.log(testString.match(testRegex_g_i));// ["Cuiht", "CUIHT", "cuiht"]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值