正則表達式:(?=a)是什么意思?


 

1.(?=a) 表示我們需要匹配某樣東西的前面。

2.(?!a) 表示我們需要不匹配某樣東西。

3.(?:a) 表示我們需要匹配某樣東西本身。

4.(?<=a) 表示我們需要匹配某樣東西的后面。

5.(?<!a) 表示我們需要不匹配某樣東西,與(?!a)方向相反

例子說明:

1.(?=a):

 console.log("我是中國人".replace(/我是(?=中國)/, "rr"))

打印出:rr中國人    (匹配的是中國前面的'我是')

2.(?!a):

console.log("我是中國人".replace(/(?!中國)/, "rr"))

打印出:rr我是中國人  

3.(?:a):

 console.log("我是中國人".replace(/(?:中國)/, "rr"))

打印出:我是rr人

4..(?<=a):

console.log("我是中國人".replace(/(?<=中國)人/, "rr")) 

打印出:我是中國rr

5.(?<!a):

  console.log("我是中國人".replace(/(?<!中國)/, "rr")) 

打印出:rr我是中國人

 

 

一些正則實際使用

去除字符串中的中文

console.log("aaa我是中國人111".replace(/[^u4E00-u9FA5]/g, "")) // 去除中文,輸出:'aaa111' 

去除字符串中的英文

console.log("aaa我是中國人111".replace(/([a-z])+/g, "")) // 去除英文,輸出:'我是中國人111'

去除字符串中的數字

console.log("aaa我是中國人111".replace(/(d)+/g, "")) // 去除數字,輸出:'aaa我是中國人' 

數字格式化

console.log("1234567890".replace(/B(?=(?:d{3})+(?!d))/g,",")) 
// 輸出:'1,234,567,890'

去除ip地址

console.log("192.168.0.1".replace(/((2[0-4]d|25[0-5]|[01]?dd?).){3}(2[0-4]d|25[0-5]|[01]?dd?)/,"rr"))
// 輸出:'rr'

 

 

 參考鏈接https://juejin.im/post/5ceb7d9df265da1b8811ba7f


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM