zoukankan      html  css  js  c++  java
  • 正则表达式(TypeScript, JavaScript)

    课题

    1. 使用正则表达式匹配字符串
      使用正则表达式 "d{3}-(d{4})-d{2}" 匹配字符串 "123-4567-89"
      返回匹配结果:’"123-4567-89" 以及 "4567"
    2. 使用正则表达式替换字符串(模式)
      使用正则表达式 "(d+)-(d+)-(d+)" 匹配字符串 "123-4567-89"
      使用模式字符串 "$3-$1-$2" 替换匹配结果,返回结果 "89-123-4567"。
    3. 使用正则表达式替换字符串(回调)
      使用正则表达式 "d+" 匹配字符串 "123-4567-89"
      将匹配结果即三个数字串全部翻转过来,返回结果 "321-7654-98"。
    4. 使用正则表达式分割字符串
      使用正则表达式 "%(begin|next|end)%" 分割字符串"%begin%hello%next%world%end%"
      返回正则表达式分隔符之间的两个字符串 "hello" 和 "world"。

    TypeScript / JavaScript

    const s = '123-4567-89,987-6543-21';
    const r = /d{3}-(d{4})-d{2}/g;
    if (r.test(s)) // if (s.match(r))
        console.log("Found matches:");
    r.lastIndex = 0;
    let m;
    for (let i = 0; m = r.exec(s); i++)
        m.forEach((v, j) => console.log(`group ${i},${j} : ${v}`));
    r.lastIndex = 0;
    [...s.matchAll(r)].forEach((m, i) => m.forEach((v, j) => console.log(`group ${i},${j} : ${v}`)));
    
    const r2 = /(d+)-(d+)-(d+)/g;
    console.log(s.replace(r2, '$3-$1-$2'));
     
    const r3 = /d+/g;
    const s3 = s.replace(r3, substring => substring.split('').reverse().join(''));
    console.log(s3);
     
    const r4 = /%(?:begin|next|end)%/g;
    const s4 = '%begin%hello%next%world%end%';
    console.log(s4.split(r4).join(','));
    
    /*
    Found matches:
    group 0,0 : 123-4567-89
    group 0,1 : 4567
    group 1,0 : 987-6543-21
    group 1,1 : 6543
    group 0,0 : 123-4567-89
    group 0,1 : 4567
    group 1,0 : 987-6543-21
    group 1,1 : 6543
    89-123-4567,21-987-6543
    321-7654-98,789-3456-12 
    ,hello,world,
    */
    
  • 相关阅读:
    huffman压缩解压文件
    C++ fstream 详解
    huffman编码
    ios cocoapods
    POI2Vec: Geographical Latent Representation for Predicting Future Visitors
    latex生成pdf 出现missing$ inserted
    矩阵、向量求导法则

    矩阵范数求导
    hive
  • 原文地址:https://www.cnblogs.com/zwvista/p/9011445.html
Copyright © 2011-2022 走看看