GenweiWu / Blog

个人技术能力提升
MIT License
4 stars 0 forks source link

js 正则 #56

Open GenweiWu opened 5 years ago

GenweiWu commented 5 years ago

资料

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

GenweiWu commented 5 years ago

下面这些怎么实现?

1、string.repalceAll ?

"/aa/bb/cc".replace(new RegExp("/[^/]+","gm"),"")
""

2、string.replaceFirst ?

"/aa/bb/cc".replace(new RegExp("/[^/]+","m"),"")
"/bb/cc"
"/11/22/33".replace(new RegExp("/[^/]+","m"),"")
"/22/33"

replace默认匹配第一个,g表示匹配所有,m表示进行多行匹配

GenweiWu commented 5 years ago

匹配和捕获

//1
'/a/b/c'.match('/[^/]+/[^/]+/[^/]+')
//2
'/a/b/c'.match('(/[^/]+)(/[^/]+)(/[^/]+)')
//3
'/a/b/c'.match('(?<group1>/[^/]+)(?<group2>/[^/]+)(?<group3>/[^/]+)')

image

理解

  1. 0,1,2可以理解成group0,group1,group2
  2. 增加()就会增加子group匹配
  3. 使用?<name>来得到命名的group匹配

参考