1. Match numbers
isNAN
Only valid for numbers
const hd='abc123bcd';
let nums=[...hd].filter(a=>!Number.isNaN(parseInt(a))).join('')
\d
Escape characters to match numbers
console.log(hd.match(/\d/g).join(''));
2. Literal creation of regular expressions
test
Check whether it contains
const hd="houdun.com"
console.log(/@/.test(hd)); //hd里面是否包含@ 返回false
eval
Test expression
let a="u"
console.log(eval(`/${
a}/`).test(hd)); // true
3. Use objects to create regular rules
g
Indicates a global matchi
not case sensitive\w
Match letters or numbers or underscoresRegExp
Regular way to create objects
// 创建对象的方式找u
const hd='www.baidu.com'
let a='u'
let reg=new RegExp(a,'g')
console.log(reg.test(hd));
- Dynamic matching string highlighting (retrieval)
<div>www.baidu.con</div>
<script>
const con = prompt('请输入要的动态匹配的字符串')
const reg = new RegExp(con, 'g')
const div = document.querySelector('div')
div.innerHTML= div.innerHTML.replace(reg, search => {
console.log(search);
return `<span style="color:red">${
search}</span>`
})
<script>
4. Use of selectors
|
Represents the selector, nested on both sides are expressions
let hd="www.baidu.com"
console.log(/a|aaab/.test(hd)); // true
const tel='020-9999999'
// \d{7,8} // 表示找到7-8位以上数字
console.log(/(010|020)\-\d{7,8}/.test(tel)); // true
5. Use of atomic groups and atomic tables
()
Represents the atom table[]
The difference between indicating the atomic group
注意
[]
and is that every character in it can be matched, but the characters in are used as a whole, and can also be separated by | as expressions()
[]
()
let reg = /[123456]/;
let hd = "123123"
console.log(hd.match(reg)); // 1
let reg = /(1236|456)/; // 当表达式进行匹配(前面的不符合规则)
let hd = "123456"
console.log(hd.match(reg)); // 456
6. Escape characters
\d
represents a number [0-9]^h
The restriction boundary character indicates that it starts with h+
represents one or more\w
Represents any letter or underscore.
Two meanings of dot
// 1. 除换行外任何字符
// 2. 普通点(要进行转义“\.”)
const price=23.34 // 注意边界的限定
console.log(/\d+\.\d+/.test(price));
Using escapes in objects
const prices=12.34
const reg=new RegExp("\\d+\\.\\d+")
console.log(reg.test(prices));
7. Character boundary constraints (interval limitation)
^
limit start boundary$
limit end boundary
const hd="hd333abc3"
console.log(/\d/.test(hd)); // true
// 限制开始必须为数字
console.log(/^\d/.test(hd)); //false
// 限制开始与结束必须为数字
console.log(/\d$/.test(hd)); // true
// 1. 限定英文字母3-6位 // 至少3位(加结束边界符有上线)
const halist='abcccccccccc'
console.log(/^[a-z]{3,6}$/.test(halist)); //false
7.1 Start and end boundaries for numbers and letter intervals
regular expression | Ranges |
---|---|
[0-9] | 0~9 |
[1-9][0-9] | 10~99 |
1[0-9]{2} | 100~199 |
2[0-4][0-9] | 200~249 |
25[0-5] | 250~255 |
[1-9][0-9][0-9]{0,2} | 10~9999 |
[1-5][0-9]{4} | 10000~59999 |
const halist='11'
// 开始边界1-9结束边界0-9 取值范围为[1-99]
console.log(/^[1-9][0-9]{0,1}$/.test(halist)); //true
// 说明 ab{1,3},就表示a,后面紧跟的b出现最少1次最多3次
let t="1"
console.log(/^([1-9]|[1-9][0-9])$/.test(t)); // 与上述相等
let s="cde"
// 表示这一段是abc、bcd、cde三者之一均可,顺序也必须一致
console.log(/^(abc|bcd|cde)$/.test(s)); // true
8. Metacharacters
d
Match numbersD
Matches everything except the numbers
const hd = '010-1999999'
console.log(/\d{3}-\d{6,9}/g.test(hd)); // true
const hdList = 'ABCD 20210'
console.log(/\D+/.test(hdList)); // true
^
Starting with something^1
means starting with 1, etc.- Used in an atomic group to indicate other than starting with something
/[^ -\d:,] 除了以 - \d : ,开头的都匹配
const p=`张三:010-999,
李四:020-666`
console.log(p.match(/[^-\d:,\s]+/g)); // ['张三', '李四']
\s
Matches whitespace (including whitespace)\S
except blank
console.log(/\s/.test(' ')); // true
console.log(/\S/.test(' ')); // false(只要有一个不是空白就是true)
9. w and W metacharacters
\w
Represents an alphanumeric underline\W
Indicates except alphanumeric and underscore
const hd='abc123_-'
console.log(hd.match(/\w+/g)); // ['abc123_']
// 1. 练习匹配邮箱
const email='[email protected]'
console.log(email.match(/\w+\@+\w+\.+\w+/g)); // 匹配邮箱
// 2. 做限制匹配邮箱
const emails='&&&[email protected]'
console.log(emails.match(/^\w+\@+\w+\.+\w+$/g)); // 做开头与结尾的限制
10. Dot character
.
Represents any character except line breaks
const hd = 'houduan.com'
console.log(hd.match(/.+/gi)); //['houduan.com']
// 匹配网址中 .的转义
const url='https://www.baidu.com'
console.log(url.match(/https?:\/\/\w+\.\w+.\w+/));
// 空格的两种匹配方式
const tel='010 - 1999999'
console.log(tel.match(/\d+ - \d{3,9}/));
// 或
console.log(tel.match(/\d+\s-\s\d{3,9}/));
11 matches all characters
[]
The data placed in the atomic group is optional[\s\S] [\d\D]
Can match all characters
const hd='ab'
console.log(hd.match(/[ab,,,xxx]+/g));
12. g and i modifiers
i
Indicates case insensitivityg
global match
const hd='HuUadd'
console.log(hd.match(/u/gi)); // ['u','U']
// 大小写U替换成@
console.log(hd.replace(/u/gi,'@')); // H@@add
13. m match modifier
\s
blank*
Indicates 0 or more\d
number.
Any character except newlinem
Convert to one line and process separately
let hd = `
#1 js,200元 #
#2 php,300元 #
#9 houdunren.com #测试
#3 node.js,180 #
`
console.log(hd.match(/\s*#\d+\s+.+\s+#\s+/g));
const data = (hd.match(/^\s*#\d+\s+.+\s+#$/gm)).map(v => {
v = v.replace(/\s*#\d+\s*/, '').replace(/#/, '')
let [name, price] = v.split(',')
return {
name, price }
})
console.log(data);
// [
// { name: 'js', price: '200元 ' },
// { name: 'php', price: '300元 ' },
// { name: 'node.js', price: '180 ' }
// ]
14. Hanzi and character attributes
[L]
The L attribute proves that it is a letter[P]
Match only punctuation characters[sc=Han]
// Match Chineseu
Wide byte matching, only half of the match
注意
Check whether letters must be combined with u
const hd='houduanren2010,正则'
console.log(hd.match(/\p{L}/gu)); //['h', 'o', 'u', 'd','u', 'a', 'n', 'r','e', 'n', '正', '则']
console.log(hd.match(/\p{P}/gu)); // [',']
console.log(hd.match(/\p{sc=Han}/gu)); // [ '正', '则' ]
let str="SY"
console.log(str.match(/[SY]/u)); // S
15. Use of lastIndex
lastIndex
Record the subscript of the last search- This attribute can be used to match and push each data into a new array.
let hd = "houdunren";
// console.log(hd.match(/\w/g));
let reg = /\w/g;
console.log(reg.lastIndex); // 0
console.log(reg.exec(hd)); //["h"]
console.log(reg.lastIndex); // 1
console.log(reg.exec(hd)); //['0']
const data=[]
while ((res = reg.exec(hd))) {
data.push(res[0])
console.log(res);
}
console.log(data); // ["u","d"....]
16. Efficient y-mode
y
Comparison of pattern and normal pattern matching
const hd = 'udunren'
const reg = /u/g
console.log(reg.exec(hd[0])); // ['u']
console.log(reg.lastIndex); // 1
console.log(reg.exec(hd[0]));
console.log(reg.lastIndex); // 3
// y模式 如何匹配的不符合就返回null
console.log('xxxxxxxxxxxxxx测试');
const hy='udunren'
const regs=/u/y
console.log(regs.exec(hy));
console.log(regs.lastIndex); // 1
console.log(regs.exec(hy));
console.log(regs.lastIndex); // 1
y
Full text search QQ number in mode
let hdqq = `模式全文检索QQ号:123456789,2836879147,846212934全文检索`
let regs = /(\d+),?/y
regs.lastIndex = 10 // 去除数字前的字符
// console.log(regs.exec(hdqq)); // 检索123456789
// console.log(regs.exec(hdqq));
// console.log(regs.exec(hdqq));
let qq = []
while ((res = regs.exec(hdqq))) qq.push(res[0])
console.log(qq); // [ '123456789,', '2836879147,', '846212934' ]
17. Atomic table
[/,.]
Indicates the existence or relationship of the characters inside (all can be matched)
let hd = 'qianduanrenu'
console.log(hd.match(/[ur]/g)); // [ 'u', 'r', 'u' ]
let tel ='2023-0-9'
// let reg=/\d{3}\-\d{1}\-\d{1}/
let reg=/^\d{4}([-\/])\d{1}[-\/]\d{1}$/
console.log(tel.match(reg));
18. Interval matching
<input type="text" name="username">
<script>
// [0-9] 区间匹配
// + 号的贪婪匹配1到多个
let hd = "2010"
console.log(hd.match(/[0-9]+/g));
let input =document.querySelector(`[name="username"]`)
input.addEventListener('keyup',function(){
if (this.value.match(/\w+/)) {
this.value=''
}
console.log(this.value.match(/\w+/));
})
</script>
19. Exclude matches
^
Used in[]
the atom table (meaning except)-
Must use escape
let hd='houdunren.com'
console.log(hd.match(/[ue]/gi)); // [ 'u', 'u', 'e' ]
// 在原子表中加^符号 , 表示排除
console.log(hd.match(/[^ue]/gi)); // ['h', 'o', 'd', 'n','r', 'n', '.', 'c','o', 'm']
// 匹配中文
let en='张三:127.0.0.1,历史127'
console.log(en.match(/[^\d,\-:.]+/g));
20. Atomic group characters are not parsed
()
Atomic group, a single one()
placed outside is an atomic group
let hd='(123456)+.'
let hds='(123456)+.'
console.log(hds.match(/()/gi)); // 原子组匹配空
console.log(hds.match(/[()]/gi)); // [ '(', ')' ]
21. Use atomic table to match all
s
Followed by s to ignore newlines
let hd = `
houdunren
hdcms
`;
console.log(hd.match(/.+/gs));
// [\s\S] 所有内容 [\d\D] 所有内容
console.log(hd.match(/[\s\S]+/)[0]);
22. Use regular expressions to manipulate DOM
()
Atomic group[]
Atomic table\1
Just take the previous atomic table*
Matches 0 or more
<!-- 1. 匹配h元素替换成空 -->
<p>ceshi</p>
<h2>123456</h2>
<h2>123456</h2>
<script>
let body = document.body
let reg=/<(h[1-6])>[\s\S]*<\/\1>/gi
body.innerHTML=body.innerHTML.replace(reg,'')
</script>
23. Use of email verification atomic groups
<input type="text" value="[email protected]" name="name">
<script>
const tyName=document.querySelector("[name='name']").value
// console.log(tyName);
// const reg=/^\w+\@\w+\.\w+/g
// console.log(tyName.match(reg));
// 1. 改进 [email protected] ()// 原子表包含|表示或
// const reg=/^[\w-]+@[\w-]+\.(com|cn|org|net|cc)$/g
// console.log(tyName.match(reg));
// 2.匹配 [email protected] // 新浪正则
// let tyName= ''
const reg=/^[\w-]+@([\w-]+\.)+(com|cn|org|cc)$/i
console.log(tyName.match(reg));
</script>
24. Atomic groups complete the replacement function
<script>
let hd = `
<h1>houdunren</h1>
<span>后盾人</span>
<h2>hdcms</h2>
`;
// 1. 把h标签替换成P标签
const reg = /<(h[1-6])>([\s\S]+)<\/\1>/gi
// 2. 注意这个$后面跟的数字表示第几个原子组里的数据
// console.log(hd.replace(reg, `<p>$2<p>`));
// 函数形式
hd.replace(reg,(p0,p1,p2)=>{
console.log(p0) // 表示<h1>houdunren</h1>
console.log(p1); //h1
console.log(p2); // 内容 houdunren
console.log(`<p>${
p2}<p>`);
})
</script>
25. Nested grouping and unrecorded grouping
?:
Used in an atomic group to indicate no recording
let hd = `
https://www.houdunren.com
http://houdunwang.com
https://hdcms.com
`;
let reg=/https?:\/\/\w+\.\w+\.(com|cn|org|cc)/gi
console.log(hd.match(reg));
let reg=/https?:\/\/((?:\w+\.)?\w+\.(?:com|cn|cc|org))/gi
let hd = `
https://www.houdunren.com
http://houdunwang.com
https://hdcms.com
`;
let reg=/https?:\/\/((?:\w+\.)?\w+\.(?:com|cn|cc|org))/gi
let urls=[]
while((res=reg.exec(hd))){
urls.push(res[1])
}
console.log(urls);
26. Multiple repeat matches and atomic groups
let hd="hdddddhd"
// 1. 在这里使用原子组 , 表示里面的内容是一个整体
console.log(hd.match(/(hd)+/gi)); // [ 'hd', 'hd' ]
let tel ='0122-9999999'
console.log(tel.match(/^0\d{2,3}\-\d{2,6}/));
27. Website username verification
<input type="text" name="username" />
<script>
document.querySelector(`[name="username"]`).addEventListener("keyup", e => {
const value = e.target.value;
let reg = /^[a-z][\w-]{2,7}$/i; // 以字母开头,且字母数字下划线2位到7位结束
console.log(reg.test(value));
});
</script>
28. Use regular expressions to complete password verification in batches
- Use regular expressions in batches in the form of arrays
<input type="text" name="password" value="" />
<script>
let input=document.querySelector("[name='password']")
input.addEventListener("keyup",(e)=>{
const value = e.target.value;
// 1. 使用数组的形式批量使用正则
const regs = [/^[a-z0-9]{5,10}$/i, /[A-Z]/, /[0-9]/];
let start=regs.every(e=>e.test(value))
console.log(start ? '正确' : '错误');
})
</script>
29. No greed
?
Indicates 0 or 1{2,10}?
The question mark used here means that only two can be matched.
let hd="hdddd"
console.log(hd.match(/hd{2,10}?/g)); // ["hdd"]
30. Tag matching prohibits greed
<body>
<main>
<span>houdunwang</span>
<span>hdcms.com</span>
<span>houdunren.com</span>
</main>
<script>
// 1.匹配span 换成h4标签并把内容描红
const main = document.querySelector('main')
// ? 禁止贪婪 表示先在第一个标签进行匹配
const reg = /<span>([\s\S]+?)<\/span>/gi
main.innerHTML = main.innerHTML.replace(reg, (p1, p2) => {
return `<h4 style="color:red">${
p2}</h4>`
})
</script>
</body>
31. Use matchAll to complete global matching
matchAll
Matches an iterable object<\/\1>
Extract content'\1'
representation match(h[1-6])
<body>
<!-- 1. 获取标签里面的数据 -->
<h1>houdunren.com</h1>
<h2>hdcms.com</h2>
<h1>测试</h1>
</body>
<script>
let reg = /<(h[1-6])>([\s\S]+?)<\/\1>/gi
const body=document.body
console.dir(body.innerHTML.match(reg)) //"h1>houdunren.com</h1>\n\t<h2>hdcms.com</h2>\n\t<h1>后盾人</h1>"
// 注意 matchAll 匹配的是可迭代的对象
const hd=body.innerHTML.matchAll(reg)
console.log(hd); // 可迭代对象
let contents=[]
for (const iterator of hd) {
console.log(iterator);
contents.push(iterator[2])
}
console.table(contents);
</script>
32. Compatible with matchAll method for lower version browsers
<body>
<h1>houdunren.com</h1>
<h2>hdcms.com</h2>
<h1>测试</h1>
</body>
<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];
}
};
let body = document.querySelector("body").innerHTML;
let search = body.matchAll(/<(h[1-6])>([\s\S]+?)<\/\1>/i);
console.log(search);
</script>
33. Use exec to complete global matching
<body>
<h1>houdunren.com</h1>
<h2>hdcms.com</h2>
<h1>测试</h1>
</body>
<script>
let reg = /<(h[1-6])>[\s\S]+?(\/\1)/gi
const body = document.body.innerHTML
// console.log(reg.exec(body));
// console.log(reg.exec(body));
let contents = []
while ((res = reg.exec(body))) {
contents.push(res)
}
console.log(contents);
// 1.封装函数的方式进行匹配
function search(string,reg) {
let result = [];
while ((res = reg.exec(string))) {
result.push(res);
}
return result;
}
let content=search(document.body.innerHTML, /<(h[1-6])>[\s\S]+?(\/\1)/gi)
console.dir(content);
</script>
34. String regular method
search方法
Returns the subscript when the character is matched successfully.match
Returns an array of all characters matched
let search='hd123hd'
console.log(search.search(/\h/gi)); // 0
let hd = `
https://hdcms.com
http://www.sina.com.cn
https://www.houdunren.com
`;
let reg = /https?:\/\/(\w+\.)?(\w+\.)+(com|cn|org|cc)/gi;
console.dir(hd.match(reg));
matchAll
Return iterable data
let hd = `
https://hdcms.com
http://www.sina.com.cn
https://www.houdunren.com
`;
let reg = /https?:\/\/(?:\w+\.)?(?:\w+\.)+(?:com|cn|org|cc)/gi;
for (const iterator of hd.matchAll(reg)) {
console.log(iterator);
}
let hdcms = "2020/09/12";
console.log(hdcms.split(/[-\/]/));
35. Replacement of $ symbol in regular expressions
// 1. $` 替换内容前面的字符
// 2. $' 替换内容后面的字符
// 3. $& 匹配自己本身的内容
const tel="2023/2/18"
// / 替换成-
console.log(tel.replace(/\//g,"-")); // 2023-2-18
const tels="(010)999999 (202)999999999"
const reg=/\((\d{3,4})\)(\d{6,12})/g
// 1. $1 表示010 202 这个组
// 2. $2表示999...这个组
console.log(tels.replace(reg, '$1-$2')); // 010-999999 202-999999999
const con="=测试="
// 1. 在测试前后分别加上=
console.log(con.replace(/测试/,"$`")); // === ,把测试替换成=
console.log(con.replace(/测试/,'$&')); // =测试= , 匹配自己本身
console.log(con.replace(/测试/,'$`$&$`'));
36. Use of atomic groups in projects
- Add s to http, add www without www to only match hdcms and houdun people
<main>
<a style="color:red" href="http://www.hdcms.com">
开源系统
</a>
<a id="l1" href="http://houdunren.com">后盾人</a>
<a href="http://yahoo.com">雅虎</a>
<h4>http://www.hdcms.com</h4>
</main>
<script>
// 1. 给http加上s , 没有www加上www 只匹配hdcms与houdun人
const mainList = document.querySelector("body main")
const reg = /(<a.*href=['"])(http?)(:\/\/)(www\.)?(hdcms|houdunren)/gi
mainList.innerHTML = mainList.innerHTML.replace(reg, (p1, ...p2) => {
p2[1] += 's'; // 可以判断是否有s
p2[3] = p2[3] || "www."
return p2.splice(0, 5).join('')
})
</script>
37. Aliasing atomic groups
?<con>
Take an alias
<script>
let hd = `
<h1>houdunren</h1>
<span>测试</span>
<h2>hdcms</h2>
`;
// 1. 取别名的方式拿取值
// 2. ?<con>取别名
const reg = /<(h[1-6])>(?<con>.*)<\/\1>/gi
console.log(hd.replace(reg, `<h4>$<con></h4>`));
</script>
Use atomic group aliases to optimize regular expressions
<main>
<a id="hd" href="https://www.houdunren.com">后盾人</a>
<a href="https://www.hdcms.com">hdcms</a>
<a href="https://www.sina.com.cn">新浪</a>
</main>
<!-- 说明: 把连接提取成link:连接 , title:内容 -->
<script>
const main = document.querySelector('body main')
const reg = /<a.*?href=(['"])(?<link>.*?)\1>(?<title>.*?)<\/a>/gi
console.log(main.innerHTML.match(reg)); // "<a id=\"hd\" href=\"https://www.houdunren.com\">后盾人</a>""\"""https://www.houdunren.com""后盾人"
// groups:{ link: 'https://www.houdunren.com', title: '后盾人' }
const Lists = []
for (const iterator of main.innerHTML.matchAll(reg)) {
Lists.push(iterator["groups"]);
}
console.log(Lists);
</script>
38. Regular and string methods
- String methods
match
matchAll
search
replace
- regular method
test
withexec
<input type="text" name="email" />
<script>
const mail = document.querySelector(`[name="email"]`);
mail.addEventListener("keyup", e => {
let value = e.target.value;
let flag = /^[\w-]+@(\w+\.)+(com|org|cn)$/i.test(value);
console.log(flag);
});
</script>
const datalist ="前端开发1不断分享视频教程,前端开1发网址是 houdunren.com前端开发1前端开发1"
//exec match
let reg = /前端开发1/g;
let count = 0;
while ((res = reg.exec(datalist))) {
count++;
}
console.log(reg.lastIndex);
console.log(reg.exec(datalist)); //
console.log(reg.lastIndex);
console.log(reg.lastIndex);
console.log(count+1);
39. ?=
Assert match
?=
Conditional statements
公司
Add a hyperlink to the two words followed by Baidu.
<main>在公司从事前端开发已经三年了,现在的公司是百度</main>
<script>
const mian=document.querySelector('main')
let reg=/公司(?=是百度)/g // 后面是谁的
mian.innerHTML=mian.innerHTML.replace(reg, `<a href="">$&</a>`)
</script>
Use assertions to standardize prices
- It is required to add .00 to the number in front of yuan
let lessons = `
js,200元,300次
php,300.00元,100次
node.js,180元,260次
`;
const reg = /(\d+)(.00)?(?=元)/gi
lessons=lessons.replace(reg, (p1, ...arg) => {
arg[1] = arg[1] || '.00'
return arg.splice(0,2).join('')
})
console.log(lessons);
40. ?<=
Assert match
?<=
Conditional statement (indicating taking the previous assertion)
- Replace all links with https://baidu.com
<main>
<a href="https://baidu.com">百度</a>
<a href="https://yahoo.com">雅虎</a>
</main>
<script>
// 1. ?<= 条件语句 (表示取前面的断言)
let hd = 'www.baidu.com'
const reg = /(?<=www.)\w+/gi
console.log(hd.match(reg)); // ['baidu']
// 2. . 点字符表示除了换行符的任意字符
const mian=document.querySelector('main')
const regs=/(?<=href=(["'])).+(?=\1)/gi
mian.innerHTML=mian.innerHTML.replace(regs,`https:baidu.com`)
</script>
Obfuscating phone numbers using assertions
let users = `
向军电话: 12345678901
后盾人电话: 98745675603
`;
let reg = /(?<=\d{7})\d+/gi
users = users.replace(reg, v => {
return "*".repeat(4)
})
console.log(users);
41. ?!
Assert match
?!
The conditional statement indicates that the following does not belong to anyone
- Match English words that are not followed by numbers
const name='abcd123abcdefgh'
const reg=/[a-zA-Z](?!\d+)/gi //后面不是数字
console.log(name.match(reg)); // ['a', 'b', 'c', 'a','b', 'c', 'd', 'e','f', 'g', 'h']
42. Restrict usernames
<body>
<input type="text" name="username">
<script>
// 1. 限制用户名不能为张三
const username=document.querySelector(`[name="username"]`)
username.addEventListener('keyup',function(){
const reg=/^(?!.*张三.*)[a-z]{1,5}$/gi
console.log(this.value.match(reg));
})
</script>
</body>
43. ?<!
Assert match
const name = 'abcd123abcdefgh'
const reg = /[a-zA-Z]+(?<!\d+)/gi //前面不是数字
console.log(name.match(reg)); //
let hd = "hdcms99houdunren";
let regs = /(?<!\d+)[a-z]+/gi;
console.log(hd.match(regs));
44. Use assertion elimination to unify data
- Replace not
oss
all withoss
<main>
<a href="https://www.houdunren.com/1.jpg">1.jpg</a>
<a href="https://oss.houdunren.com/2.jpg">2.jpg</a>
<a href="https://cdn.houdunren.com/3.jpg">3.jpg</a>
<a href="https://houdunren.com/4.jpg">后盾人</a>
</main>
<script>
const main=document.querySelector("main")
const reg=/https?:\/\/([a-z]+)?(?<!=oss)\..+?(?=\/)/gi
main.innerHTML=main.innerHTML.replace(reg,v=>{
return "https://oss.houdunren.com";
})
</script>
Summarize () [] {}
the different meanings of 1.0
- () is to extract the matching string. There are as many corresponding matching strings as there are () in the expression.
- (\s*) represents a string of consecutive spaces.
- [] is the character range that defines matching. For example, [a-zA-Z0-9] means that the characters at the corresponding positions must match English characters and numbers. [\s*] represents a space or * sign.
- {} is generally used to indicate the length of the match. For example, \s{3} indicates matching three spaces, and \s{1,3} indicates matching one to three spaces.
- (0-9) matches '0-9' itself. [0-9]* matches numbers (note that there is * after it, it can be empty) [0-9]+ matches numbers (note that there is
+ after it, it cannot be empty) {1-9} is written incorrectly. - [0-9]{0,9} represents a numeric string with a length of 0 to 9.
Parentheses () are groups, mainly used to limit the range of multi-select structures/grouping/capture text/look around/special mode processing
examples:
- (abc|bcd|cde) means that this paragraph can be any one of abc, bcd, and cde, and the order must be consistent.
- (abc)?, means that this group either appears together or does not appear. If it appears, it will appear in the order within this group.
- (?:abc) means that a group like abc is found, but it is not recorded or saved in a variable, otherwise it can be passed through the variable, otherwise it can be passedvariable, otherwise you can use $3 gets the content matched by (ccc), while $4 gets the content matched by (eee), because the first pair of brackets does not save the variable.
- a(?=bbb) Sequential look around means that a must be followed by 3 consecutive b’s
- (?i:xxxx) Case-insensitive (?s:.*) Cross-line matching. Can match carriage return characters
Square brackets are a single match, character set/excluded character set/named character set
example:
- [0-3] means that the characters found at this position can only be four numbers from 0 to 3. It is similar to (abc|bcd|cde), but the parentheses can match multiple consecutive characters, and A pair of square brackets can only match a single character
- [^0-3] means that the characters found at this position can only be all characters except 0 to 3.
- [:digit:] 0-9 [:alnum:] A-Za-z0-9
There is an essential difference between () and []
- The content inside () represents a subexpression. () itself does not match anything, nor is it restricted to matching anything. It just treats the content in parentheses as the same expression, such as (ab){1,3 }, it means that ab appears together at least once and at most 3 times. If there are no brackets, ab{1,3} means a, followed by b appearing at least once and at most 3 times. Also, parentheses are important in matching patterns.
- [] means that the matching characters are in [] and can only appear once, and special characters written in [] will be matched as ordinary characters. For example, [(a)] will match the three characters (, a,).