Regular learning notes-2

Regular expression

1. The use of atomic tables
// 1. 原子表的简单使用
let tel = '2020-04-06'
//let tel = '2020/04/06'
console.log(tel.match(/^\d{4}-\d{2}-\d{2}$/))
//[-\/]表示-或者/ 都可匹配
console.log(tel.match(/^\d{4}[-\/]\d{2}[-\/]\d{2}$/))
//()如果之后的格式与其进行相同\1即可
console.log(tel.match(/^\d{4}([-\/])\d{2}\1\d{2}$/));
// 2.原数表中的顺序从小到大,在a-z否则会报错
// 数字检测
const num = "2";
console.log(/[0-3]/.test(num)); //true
//字母检测
const hd = "e";
console.log(/[a-f]/.test(hd)); //true
//3.原子表中有些正则字符不需要转义,如果转义也是没问题的,可以理解为在原子表中. 就是小数点
let str = "(houdunren.com)+";
console.table(str.match(/[().+]/g));
//使用转义也没有问题
console.table(str.match(/[\(\)\.\+]/g));
// 4. 匹配所有的内容
      let hd = ` houdunren 
        hdcms
        `;
      // 其中\d\D \w\W 都可以
      console.log(hd.match(/[\s\S]+/g));
// 正则操作DOM元素
  <h1>houdunren.con houdunwang.com</h1>
  <h2>baidu.com</h2>
  //js
   let body = document.body;
   let reg = /<(h[1-6])>[\s\S]*<\/\1>/gi;
  body.innerHTML = 
  body.innerHTML.replace(reg, "");
  // 原子表中^ 表示除了
Atomic table Description
[] Matches only one of the atoms
[^] Only match any atom "except" the character in it
[0-9] Match any number from 0-9
[a-z] Match any letter in lowercase az
[A-Z] Match any letter in uppercase AZ
2. Use of Atomic Groups
//1. 如果一次要匹配多个元子,可以通过元子组完成
let str = `<h1>as</h1>
        <h2>dfd</h2>
      `;
let reg = /<(h[1-6])>[\s\S]*<\/\1>/g;
console.log(str.match(reg));
// 
The difference between the atom group and the atom table is that the atom group matches multiple elements at a time, while the atom table matches any character

1. When the g pattern modifier is not added, only the first one is matched, and the matched information contains the following data
2. Using atomic group matching in the match, each group of data will be returned to the result

variable Description
0 Full content matched
1,2… Matched atom group
index Position in the original string
input Original string
groups Named group
// 2. 匹配邮箱
<input type="text" name="email" value="[email protected]" />

      let email = document.querySelector(`[name="email"]`).value;
      console.log(email);
      let reg = /^[\w-]+@([\w-]+\.)+(com|org|cc|cn|net)$/i;
      console.log(email.match(reg));
//3. 原子组引用完成替换
      let str = `
      <h1>内容1部分</h1>
      <h2>内容2部分</h2>
      <p>内容3部分</p>
      `;
      let reg = /<(h[1-6])>([\s\S]+)<\/\1>/gi;
      console.log(str.match(reg));
      console.log(str.replace(reg, "<p>$2</p>"));
      let res = str.replace(reg, (p0, p1, p2) => `<p>${
      
      p2}</p>`);
      // p0 指的是全部内容 p1指的是从外像内第一层
      console.log(res);
// 4. 嵌套分组与不记录分组
      let url = `
         http://www.baidu.com
         https://www.sina.com
         https://www.qq.com
      `;
      let reg = /(?:http|https)?:\/\/((?:\w+\.)?\w+\.(?:com|cn|net))/gi;
      console.log(url.match(reg));
      let urls = [];
      while ((res = reg.exec(url))) {
    
    
        urls.push(res[1]);
      }
      // ?: 在原子组中不进行记录 也就是没有\1 $1
      console.log(urls);
3. Multiple repetitive matches
// 贪婪语法
      let str = "www.baiduww.com";
      console.log(str.match(/w+/g));
      // 重复一次或更多次
      console.log(str.match(/w?/g));
      // 重复零次或一次
      console.log(str.match(/w*/g));
      // 重复零次或更多次
      console.log(str.match(/w{2}/g));
      // 重复n次
       console.log(str.match(/w{2,}/g));
      //重复n次或更多次
      console.log(str.match(/w{1,3}/g));
      //重复n到m次
    
// 重复匹配对原子组影响与电话正则
 let tel = "010-99999999";
      console.log(tel.match(/^0\d{2,3}-\d{7,8}$/));
      console,log(tel.match(/(10)+/))
// 验证用户名
 <input type="text" name="username" />
      document
        .querySelector(`[name="username"]`)
        .addEventListener("keyup", (e) => {
    
    
          let reg = /^[a-z][\w-]{2,7}$/i;
          let val = e.target.value;
          console.log(val);
          console.log(reg.test(val));
        });
  // 利用多个数组进行验证
      document
        .querySelector(`[name="password"]`)
        .addEventListener("keyup", (e) => {
    
    
          let regs = [/^[a-z0-9]{5,9}$/i, /[A - Z]/, /\d/];
          let val = e.target.value;
          let status = regs.every((e) => e.test(val));
          console.log(status ? "正确" : "不包含");
        });
4. Prohibition of greed
// 禁止贪婪标签替换
   <main>
      <span>www.baidu.com</span>
      <span>www.sina.com.cn</span>
      <span>dsfdsfds</span>
    </main>
      const main = document.querySelector("main");
      const reg = /<span>([\s\S]+?)<\/span>/gi;
      let str = "";
      main.innerHTML = main.innerHTML.replace(reg, (v, p1) => {
    
    
        console.log(`<h4>${
      
      p1}</h4>`);
        return `<h4>${
      
      p1}</h4>`;
      });

5. Global Match
// 全局匹配
<body>
    <main>
      <h1>内容1部分</h1>
      <h2>内容1部分</h2>
      <h3>内容1部分</h3>
    </main>
  </body>
  <script>
    let val = /<(h[1-6])>([\s\S]+?)<\/\1>/gi;
    let body = document.body;

    let hd = body.innerHTML.matchAll(val);
    console.log(hd);
    let arr = [];
    for (const iterator of hd) {
    
    
      arr.push(iterator[2]);
    }
    console.log(arr);
  </script>
 // 兼容方法
   String.prototype.matchAll = function (reg) {
    
    
      let res = this.match(reg);
      if (res) {
    
    
        let str = this.replace(res[0], "^".repeat(res[0].length));
        let match = str.matchAll(reg) || [];
        return [res, ...match];
      }
    };
// 正则的方法匹配
   function search(param, reg) {
    
    
      let result = [];
      while ((ee = reg.exec(param))) {
    
    
        result.push(ee);
      }
      return result;
    }
    let matchs = search(document.body.innerHTML, /<(h[1-6])>[\s\S]+?<\/\1>/gi);
    console.log(matchs);
6. Regular methods
// 字符串常用的方法
//search 方法用于检索字符串中指定的子字符串,也可以使用正则表达式搜索,返回值为索引位置
let str = "houdunren.com";
console.log(str.search("com"));
console.log(str.search(/\.com/i));
//match 直接使用字符串搜索
let str = "houdunren.com";
console.log(str.match("com"));
//matchAll  在新浏览器中支持使用 matchAll 操作,并返回迭代对象
let str = "houdunren";
let reg = /[a-z]/ig;
for (const iterator of str.matchAll(reg)) {
    
    
  console.log(iterator);
}
// split 用于使用字符串或正则表达式分隔字符串,下面是使用字符串分隔日期
let str = "2023-02-12";
console.log(str.split("-")); //["2023", "02", "12"]
let str = "2023/02-12";
console.log(str.split(/-|\//));
// replace 方法不仅可以执行基本字符替换,也可以进行正则替换,下面替换日期连接符
let str = "2023/02/12";
console.log(str.replace(/\//g, "-")); //2023-02-12

variable Description
$$ Insert a "$"
$& Insert matching string
$` Insert the content to the left of the currently matched substring.
$’ Insert the content to the right of the currently matched substring.
$n If the first parameter is a RegExp object, and n is a non-negative integer less than 100, then insert the string matching the nth bracket. Tip: Index starts from 1
// 正则方法
// test 检测输入的邮箱是否合法
<body>
  <input type="text" name="email" />
</body>

<script>
  let email = document.querySelector(`[name="email"]`);
  email.addEventListener("keyup", e => {
    
    
    console.log(/^\w+@\w+\.\w+$/.test(e.target.value));
  });
</script>
// exec 不使用 g 修饰符时与 match 方法使用相似,使用 g 修饰符后可以循环调用直到全部匹配完
<body>
  <div class="content">
    后盾人不断分享视频教程,后盾人网址是 houdunren.com
  </div>
</body>

<script>
  let content = document.querySelector(".content");
  let reg = /(?<tag>后盾)人/g;
  let num = 0;
  while ((result = reg.exec(content.innerHTML))) {
    
    
    num++;
  }
  console.log(`后盾人共出现${
      
      num}次`);
</script>

7. Assertion match
// 零宽先行断言
let val = "<p align=right>标题</p>"
// 将align换成text-align
let str = val.splace(/align(?=right)?/gi,"text-align")
console.log(str)
//零宽后行断言
// 将right替换为center
let str = val.splace(/(?<=align=)right?/gi,"center")
console.log(str)
//(?!exp) 零宽负向先行断言 后面不能出现 exp 指定的内容 使用 (?!exp)字母后面不能为两位数字
let hd = "houdunren12";
let reg = /[a-z]+(?!\d{2})$/i;
console.table(reg.exec(hd));

//(?<!exp) 零宽负向后行断言 前面不能出现exp指定的内容 获取前面不是数字的字符
let hd = "hdcms99houdunren";
let reg = /(?<!\d+)[a-z]+/i;
console.log(reg.exec(hd)); //hdcms

Guess you like

Origin blog.csdn.net/weixin_45176415/article/details/105339635