x(?=y)、x(?!y)、x*?、x+? Love The Way You Lie 2023-06-07 05:46 3阅读 0赞 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> </body> <script type="text/javascript"> /* 正则表达式中特殊字符的含义(数量词(Quantifiers)): x(?=y) :只有当 x 后面紧跟着 y 时,才匹配 x。(x后面是y) x(?!y) :只有当 x 后面不是紧跟着 y 时,才匹配 x。(x后面没有y) */ //运用:你现在想在aaaabab选择b前面的a const re = /\w(?=b)/g; const text = 'aaaabab'; console.log(text.match(re));//["a", "a"] //突然你又想在aaaabab选择不是b前面的a const re2 = /\w(?!b)/g; const text2 = 'aaaabab'; console.log(text2.match(re2));//["a", "a", "a", "b", "b"] /* 正则表达式中特殊字符的含义(数量词(Quantifiers)): x*?、x+? : * 和 + 一样匹配前面的模式 x,然而匹配是最小可能匹配。 */ //贪婪匹配 const re3 = /x+/g; const text3 = 'xxxx'; console.log(text3.match(re3));//["xxxx"] //非贪婪匹配 const re4 = /x+?/g; const text4 = 'xxxx'; console.log(text4.match(re4));//["x", "x", "x", "x"] const re5 = /x{1,4}?/g;//能一个绝对不会四个 const text5 = 'xxxx'; console.log(text5.match(re5));//["x", "x", "x", "x"] /* (难度较大)将100000000变成科学计数法,100.000.000 */ let text6 = '100000000'; const re6 = /(?=(\B)(\d{3})+$)/g; console.log(text6.replace(re6, '.')); </script> </html>
还没有评论,来说两句吧...