正则表达式知识点

158 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第2天,点击查看活动详情

  • test()方法:字符串是否与正则匹配,得到true或false
let a = "testabc"; 
let reg = /test/; 
console.log(reg.test(a))//返回true 
/regex/.test('string');//正则表达式后调用test的方法
  • match()方法:得到匹配的数组
let a = 'testabc'; let reg=/test/ 
let result = a.match(reg);//输出result:["test"] 
'string'.match(/regex/);
  • replace():
  • |:或者
let reg = /dog|cat|apple/i;//i忽略大小写 
let a = 'LEo is a dog' 
console.log(reg.test(a));//返回true
  • .:元字符用于查找单个字符,除了换行和行结束符
let a = 'hut'; 
let reg = /h.t/ 
console.log(reg.test(a))//返回true
  • ?: 存在0次或1次
let reg = /colou?r/ 
let a = "color" 
let b = "colour" 
console.log(reg.test(a))//true 
console.log(reg.test(b)))//true
  • n*:匹配任何包含零个或多个 n 的字符串
let chewieRegex = /Aa*/ig
let chewieQuote = "Aaaaaaaaaaaaaaaarrrgh!" 
let result = chewieQuote.match(chewieRegex); 
console.log(result)//[ 'Aaaaaaaaaaaaaaaa' ]
  • n+:匹配任何包含至少一个 n 的字符串
let difficultSpelling = "Mississippi"; 
let myRegex = /s+/ig
let result = difficultSpelling.match(myRegex); 
console.log(result)//[ 'ss', 'ss' ]
  • []:方括号用于查找某个范围内的字符:
let reg1 = /[abc]/gi;//配置a、b、c字符 
let reg2 = /[^abc]/gi;//查找非a、b、c的字符 
let reg3 = /[0-9]/gi;//查找0-9的数字 
let reg4 = /[a-z]/gi;//查找a-z的的字符 
let reg5 =/a-z0-9/gi;//查找0至9和a至z的字符
  • ^n:匹配任何开头为 n 的字符串。n&:以n结尾的字符串
let chewieRegex = /^Aa*/ 
let chewieQuote = "Aaaaaaa!"; 
let result = chewieQuote.match(chewieRegex); 
console.log(result)//输出 ['Aaaaaaaaaaaaaaaa']
  • ?=n 量词匹配任何其后紧接指定字符串 n 的字符串
var str="Is this all there is"; 
var patt1=/is(?= all)/; 
document.write(str.match(patt1));//输出:is
  • ?!n:匹配任何其后没有紧接指定字符串 n 的字符串。
  • 贪婪模式:只要匹配上的,尽可能地保留符合的字符
let text = "<h1>Winter is coming</h1>"; let myRegex = /<.*>/; //  let result = text.match(myRegex);//["<h1>Winter is coming</h1>"]
  • 懒惰模式:懒惰模式是尽可能少去匹配上
let text = "<h1>Winter is coming</h1>"; let myRegex = /<.*?>/let result = text.match(myRegex);//["<h1>"]
  • \w:等价于集合[A-Za-z0-9_]
  • \W:等价于[^A-Za-z0-9_]
  • \d:等价于[0-9]
  • \D:等价于[^0-9]
  • \s:匹配空格
  • \S:匹配非空格字符
  • \n:匹配换行
  • \b:单词边界

个人练习所得的正则表达式

  1. 在 reRegex 中使用捕获组来匹配一个只由相同的数字重复三次组成的由空格分隔字符串
let repeatNum = "42 42 42"; 
let reRegex = /^(\d+)\s\1\s\1$/; // \1 可以匹配第一个组 
let result = reRegex.test(repeatNum); 
console.log(repeatNum.match(reRegex))
  1. 捕获组,使用美元符号($)访问替换字符串中的捕获组。
"Code Camp".replace(/(\w+)\s(\w+)/, '$2 $1'); //上面打印将返回字符串 Camp Code
  1. 捕获组,改变字符串的顺序
let str = "one two three"; 
let fixRegex = /^(\w+)\s(\w+)\s(\w+)$/; // 修改这一行 
let replaceText = "$3 $2 $1"; // 修改这一行 
let result = str.replace(fixRegex, replaceText); 
console.log(result)//打印three two one
  1. 千位分隔符

//千位运算符

let reg1 = /(?!^)(?=(\d{3})+$)/g; 
let count = "123230980890"; 
let a = count.replace(reg1,"$&,"); 
console.log(count,a)
  1. 替换匹配的数据
const data = [{key:'TEST(key1)',text:'测试1'},{key:'TEST(key2)',text:'测试2'}]
const text = 'TEST(key1)+TEST(key2)'
const deal = (str:string)=>{
    let strTwo = str.replaceAll(/TEST\(\w*\)/g,(match:string,p1:string):string=>{
      let filterArr = data.filter((item:any)=>{
        return item.key === match
      })
      return filterArr.length>0?`TEST(${filterArr[0].title})`:match;
    })
    return strTwo;
}
const textTwo = deal(text)
console.log(textTwo)//输出:TEST(测试1)+TEST(测试1)
  1. 格式化日期
/**
 * @description 格式化日期
 * @param {Date} date 时间戳 默认当前日期
 * @param {string} formatType  默认'YYYY-mm-dd' 日期格式 eg: YYYY-mm-dd HH:MM:SS
 * @return {String} 日期
 */
 const formatTime = (date: any, formatType: string = 'YYYY-mm-dd'):string => {
    formatType = formatType || 'YYYY-mm-dd';
    const year = date.getFullYear(); // 年
    const month = date.getMonth() + 1; // 月
    const day = date.getDate(); // 日
    const hours = date.getHours(); // 时
    const minutes = date.getMinutes(); // 分
    const seconds = date.getSeconds(); // 秒
    //console.log()

    // formatType eg: 'YYYY-mm-dd HH:MM:SS'、'yyy-mm-dd HH:MM'、'yyy-mm'、'yyyy'
    formatType = formatType.replace(/(YYYY|mm|dd|HH|MM|SS)/gi, function ($0: string) {
        let num = ''
        switch ($0) {
            case 'YYYY':
            case 'yyyy':
                num = formatNumber(year);
                break;
            case 'mm':
                num = formatNumber(month);
                break;
            case 'dd':
                num = formatNumber(day);
                break;
            case 'HH':
                num = formatNumber(hours);
                break;
            case 'MM':
                num = formatNumber(minutes);
            case 'SS':
                num = formatNumber(seconds);
                break;

            default:
                break;
        }
        return num;
    });
    return formatType;
}

image.png