正则学习笔记

正则表达式Regular Expression

正则表达式是一种文本模式(相当于数学中的逻辑公式)
正则表达式使用单个字符串来描述、匹配一系列某个句法规则的字符串

字符串模式

方法

search

接收参数 (接受正则对象 or 字符值模式)

方法返回的是索引值

function string_search() {
    // 正则对象
    let reg = /\d+/
    // 正则字符串
    let pattern_string = '\\d+'
    let text = 'my name is Summer, I am 26 years old!'
    let outputText = ''
    let idx = text.search(reg)
    let idx_s = text.seatch(pattern_string)
    if (~idx) {
        outputText = '索引值:' + idx + '<br>' + '\t字符值:' + text[idx]
    } else {
        outputText = '不匹配'
    }
    // 索引值:24  字符值:2
}
match

可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配

默认返回第一个匹配的值

function string_match() {
    let reg = /\d+/
    let text = '成都的邮政编码有:610000,610001,610002,610003'
    let outputText = ''
    
    let matches = text.match(reg)
    if (matches) {
        outputText = '匹配值为:' + outputText
    }
    // 匹配值为:610000
}
matchAll

返回一个包含所有匹配正则表达式及分组捕获结果的迭代器

需要全局g修饰符

function string_match_all() {
    let reg = /\d+/g
    let text = '成都的邮政编码有:610000,610001,610002,610003'
    let outputText = ''
    
    let matches = text.matchAll(reg)
    for (let match of matches) {
        outputText += '匹配值:' + match[0] + '\t索引值:' + match.index + '<br>'
    }
    
    let matchesArray = [...matches]
    // [
    // {'610000', index: 9, input: '成都的邮政编码有:610000,610001,610002,610003'},
    // ...
    // ]
}
分组 - 索引 matchAll拓展

分组使用()进行

返回一个迭代器

function groups_indexed() {
    let reg = /(\d{4})(\d{2})(\d{2})/g // matchAll 一定要加修饰符 g
    let text = '假设今天的日期是:20200202'
    let outputText = ''
    
    let matches = text.matchAll(reg)
    
    for (let match of matches) {
        // ... 
        outputText += '匹配值:' + match[0] + ', 索引值:' + match.index
        outputText += '匹配值:' + match[1] + ', 索引值:' + match.index
        outputText += '匹配值:' + match[2] + ', 索引值:' + match.index
        outputText += '匹配值:' + match[3] + ', 索引值:' + match.index
    }
    console.log([...matches])
    // 
    // [
    // 	[
    //        0: '20200202', 
    //        1: '2020', 
    //        2: '02', 
    //        3: '02',
    //        groups: undefined,
    //  	  index: 9,
    //        input: '假设今天的日期是:20200202'
    //  ]
    // ]
}
分组 - 命名 matchAll拓展

?

/(?\d{4})(?\d{2})(?\d{2})/g

function groups_indexed() {
    let reg = /(?<year>\d{4})(?<month>\d{2})(?<day>\d{2})/g // matchAll 一定要加修饰符 g
    let text = '假设今天的日期是:20200202'
    let outputText = ''
    
    let matches = text.matchAll(reg)
    
    for (let match of matches) {
        outputText += '\t匹配值:' + match[0] + ', 索引值:' + match.index + '<br>'
        for (let i = 0; i < match.length; i++) {
          outputText += '\t分组[' + i + ']:' + match[i] + '<br>'
        }

        for (let p in match.groups) {
          outputText += '\t分组[' + p + ']:' + match.groups[p] + '<br>'
        }
    }
    // console.log([...matches])
    // [
    // 	[
    //        0: '20200202', 
    //        1: '2020', 
    //        2: '02', 
    //        3: '02',
    //        groups: {
	//			  year: '2020',
    //        	  month: '02',
    //            day: '02'
	//  	  },
    //  	  index: 9,
    //        input: '假设今天的日期是:20200202'
    //  ]
    // ]
    
}
替换replace
function string_replace() {
    let reg = /(?<year>\d{4})(?<month>\d{2})(?<day>\d{2})/g
    let text = '假设今天的日期:20200202,春节放假时间:20200210'
    let replave_pattern = '$<month>-$<day>-$<year>'
    
    let new_text = text.replace(reg, replace_pattern)
    
    console.log(new_text)
    // '假设今天的日期:02-02-2020,春节放假时间:02-10-2020'
}
自定义replace - 格式化日期
//格式化日期
    function format_date(match, year, month, day, offset, string, groups) {
      console.log(match, year, month, day, offset, string, groups);
        //20210202 2021 02 02 7 今天的日期是:20210202, 春节放假时间:20210210 {year: "2021", month: "02", day: "02"}
		// 20210210 2021 02 10 24 今天的日期是:20210202, 春节放假时间:20210210 {year: "2021", month: "02", day: "10"}
      let new_date = new Date(year, month, day)

      return new_date.toDateString()
    }
    //替换-自定义
    function find_replace_custom() {
      let re = /(?<year>\d{4})(?<month>\d{2})(?<day>\d{2})/g
      let text = '今天的日期是:20210202, 春节放假时间:20210210'

      let new_text = text.replace(re, format_date)
      document.getElementById('output').innerHTML =
        '字符串模式:' +
        re.source +
        '<br>' +
        '待匹配文本:' +
        text +
        '<br>' +
        '匹配结果:' +
        '<br>' +
        new_text
    }
分割split

regexp对象模式

API方法:

source:获取正则对象的源文本
let reg = /\d+/
console.log(reg.source)
// \d+
test()

方法用于检测一个字符串是否匹配某个模式,如果字符串中含有匹配的文本,则返回 true,否则返回 false

exec()

方法用于检索字符串中的正则表达式的匹配。该函数返回一个数组,其中存放匹配的结果。如果未找到匹配,则返回值为 null。

function re_exec() {
      let re = /(?<year>\d{4})(?<month>\d{2})(?<day>\d{2})/g
      let text = '今天的日期是:20210202, 春节放假时间:20210210'
      let outputText = ''

      let match

      while ((match = re.exec(text)) !== null) {
        // console.log(match) // 数组[]
        outputText += '\t匹配值:' + match[0] + ', 索引值:' + match.index + '<br>'
        for (let i = 0; i < match.length; i++) {
          outputText += '\t分组[' + i + ']:' + match[i] + '<br>'
        }

        for (let p in match.groups) {
          outputText += '\t分组[' + p + ']:' + match.groups[p] + '<br>'
        }

      }

      if (outputText.length === 0) {
        outputText = '\t不匹配'
      }
      document.getElementById('output').innerHTML =
        '字符串模式:' +
        re.source +
        '<br>' +
        '待匹配文本:' +
        text +
        '<br>' +
        '匹配结果:' +
        '<br>' +
        outputText
    }

// 结果
匹配值:20210202, 索引值:7
	分组[0]:20210202
	分组[1]:2021
	分组[2]:02
	分组[3]:02
	分组[year]:2021
	分组[month]:02
	分组[day]:02
	匹配值:20210210, 索引值:24
	分组[0]:20210210
	分组[1]:2021
	分组[2]:02
	分组[3]:10
	分组[year]:2021
	分组[month]:02
	分组[day]:10

持续更新

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值