正则表达式学习

179 阅读1分钟

选择符

字符描述
|或,匹配左右两边任何一个满足就可以
\匹配特殊字符。
\d匹配数字字符。等价于 [0-9]
\w匹配字母、数字、下划线。等价于 [A-Za-z0-9_]
()元字组,(12|34) 表示 12 或 34 是一个整体
[]元字表,[123456] 或其中一个
[^ABC]匹配除了 [...] 中字符的所有字符
^匹配字符串的开始位置
$匹配字符串的结束位置
+表示匹配多个
let nums = "ceshi2023com10aa15bb21bb23";  
console.log(nums.match(/\d/g).join("")); // 202310152123 

let hd = "houdunren.com";  
// todo 字面量创建正则表达式  
console.log(/u/.test(hd)); // true  

// todo 使用对象创建正则表达式,'u' 代表要查找的字符,‘g’ 是修饰符,表示全局匹配 
let reg = new RegExp("u", "g");  
console.log(reg.test(hd)); // true
console.log(/[u@]/.test(hd)); // true  

let tel = "020-9999999";  
console.log(/(010|020)-\d{7,8}/.test(tel)); // true  
const num = "12121";  

let reg1 = /[123456]/;  
console.log(num.match(reg1)); // [ '1', index: 0, input: '12121', groups: undefined ] 

let reg2 = /(12|34)/;  
console.log(num.match(reg2)); // [ '12', '12', index: 0, input: '12121', groups: undefined ]  
  
let price = 23.34;  
// . 除换行外任何字符 .普通点 \. 转义字符  
// d 普通字符串 \d 数字  
console.log(/\d+\.\d+/.test(price)); // true  

let reg3 = new RegExp("\\d+\\.\\d+");  
console.log(reg3.test(price), "\\d+\\.\\d+"); // true  

let url = "https://www.houdunren.com";  
// todo (\/\/ 转义 //);(\w 匹配// 后面字符);(\. 转义 .);(\w 匹配// 后面字符);(\. 转义 .);(\w 匹配// 后面字符);  
console.log(/https?:\/\/\w+\.\w+\.\w+/.test(url)); // true  

let hd1 = "8bjlk8";  
console.log(/^\d$/.test(hd1)); // false 匹配是否已数字开头  
  
let hd3 = "houdunren 2010";  
console.log(hd3.match(/\d+/g)); // [ '2010' ]  
console.log(hd3.match(/\d/g)); // [ '2', '0', '1', '0' ]  
console.log(hd3.match(/\D+/g)); // [ 'houdunren ' ]  
  
let hd4 = `张三:010-99999999,李四:020-88888888`;  
console.log(hd4.match(/\d{3}-\d{7,8}/g)); // [ '010-99999999', '020-88888888' ]  
// todo /[^-\d:,]+/g [^] 匹配除了 [...] 中字符的所有字符  
console.log(hd4.match(/[^-\d:,]+/g)); // [ '张三', '李四' ]


let con = prompt("请输入要检测的内容,支持正则");  
let reg = new RegExp(con, "g");  
let div = document.querySelector("div");  
// todo 使用正则表达式进行查找 替换,  
// todo 输入 . 所有内容全部替换  
div.innerHTML = div.innerHTML.replace(reg, search => {  
    return `<span style="color:red">${search}</span>`;  
});  
  
document.querySelector("[name='user']").addEventListener("keyup", function() {  
    // todo /^[a-z]{3,6}$/ 表示 输入的字符 三到六 位由英文字母组成  
    let flag = this.value.match(/^[a-z]{3,6}$/);  
    console.log(flag ? "正确" : "失败");  
});