• js正则分组&引用&t贪婪&惰性


    分组

    /(d{4})-(d{2})-(d{2})/.test('2019-08-25')    // true
    RegExp.$1='2019'
    RegExp.$2='08'
    RegExp.$3='25'
    RegExp.$4=''
    RegExp.$_='2019-08-05'
    
    // 最多到RegExp.$9,没有$10,这本身是js的坑
    
    // 解决:
    '2019-08-25'.match(/(d{4})-(d{2})-(d{2})/);
    // 0: "2019-08-25"
    // 1: "2019"
    // 2: "08"
    // 3: "25"
    // groups: undefined
    // index: 0
    // input: "2019-08-25"
    // length: 4

    ES2018对正则(分组)的扩展:

    '2019-08-25'.match(/(?<year>d{4})-(?<month>d{2})-(?<day>d{2})/)
    // 0: "2019-08-25"
    // 1: "2019"
    // 2: "08"
    // 3: "25"
    // groups: {year: "2019", month: "08", day: "25"}
    // index: 0
    // input: "2019-08-25"
    // length: 4

    引用

    '2019-08-25'.match(/(d{4})-(d{2})-2/)
    // null
    
    '2019-08-08'.match(/(d{4})-(d{2})-2/)
    // 不为null
    // 最后一个  '2'  是对第二个的引用
    
    // ES2018引用
    '2019-08-25'.match(/(?<year>d{4})-(?<month>d{2})-k<month>/)    // null
    
    '2019-08-08'.match(/(?<year>d{4})-(?<month>d{2})-k<month>/)    // 不为null
    '2019-08-25'.replace(/(d{4})-(d{2})-(d{2})/,`year($1),month($2)`)
    // "year(2019),month(08)"
    // $1,$2是对前两个匹配字符串的引用

    贪婪

    尽可能多的匹配

    /.*bbb/g.test('abbbaabbbaaabbb1234');
    // 贪婪模式:会先匹配最后一个字符'4',发现不匹配之后回溯,直到匹配到'bbb'

    惰性

    尽可能少的匹配

    /.*bbb/g.test('abbbaabbbaaabbb1234');
    // 先匹配第一个字符'a',发现不匹配之后,又从第一个开始,直到匹配到'abbb'
  • 相关阅读:
    zabbix监控nginx的性能
    常用iptables命令
    shell脚本小示例
    打印菜单脚本
    ping主机脚本
    Linux网络配置脚本
    多磁盘自动分区自动挂载脚本
    深入js系列-类型(null)
    深入js系列-类型(开篇)
    first-child、last-child误解
  • 原文地址:https://www.cnblogs.com/jingouli/p/11427238.html
Copyright © 2020-2023  润新知