1.三种匹配方式
match—re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none
search—re.search 扫描整个字符串并返回第一个成功的匹配
findall—在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。
{
"node": {
"createdIndex": 285911008,
"dir": false,
"key": "/registry/ipsec/v1/default/bt2g2uh7hqddddka3e80",
"modifiedIndex": 285911049,
"ttl": 0,
"value": "apiVersion: ipsec/v1\nkind: Ipsec\nmetadata:\n creationTimestamp: \"2020-08-25T12:18:02Z\"\n labels:\n channelId: E201202004080030\n linkName: bt1s06bmfjm8f18i7ong\n nodeName: HangZhou.xiasha.pop1.oldvm.vm3\n vxlanId: v204\n name: bt2g2uh7hqddddka3e80\n namespace: default\n uid: f2660a51-7a3f-4df0-8b47-fd51973a42c5\nspec:\n ClientNetwork:\n - 172.16.2.0/24\n - 100.64.0.12/32\n Cmd: \"\"\n Eap: 291b643a-2f2f-480a-94d4-528051497298\n ErrMsg: \"\"\n IsMaster: false\n Left: 100.64.0.19\n LeftId: 183.136.237.7\n LinkName: bt1s06bmfjm8f18i7ong\n Metric: 100\n NodeName: HangZhou.xiasha.pop1.oldvm.vm3\n Prepared: true\n Right: 100.64.0.20\n RightId: 10.201.0.189\n Secret: ba72c4e4-e7bc-475a-899e-de6abd4480c0\n UpdateTimestamp: 1598357884\n Vlan: 4\n VtiCreated: true\n VtiId: 45\n VxlanId: 204\n"
}
}
上面是res的返回结果,返回的()中的内容,如果没有(),就匹配符合的内容
#匹配channelId: V501202007141416后的16位,可以换行匹配(re.MULTILINE)
comment = re.compile(r'channelId: (.{16})', re.MULTILINE)
sn = re.findall(comment,res['node']['value'])
sn_str = "".join(sn)
name_sn[i]=sn_str
2.Re库的贪婪匹配和最小匹配
Re库默认采取贪婪匹配,即输出匹配最长的子串
s = '{{"countryZh":"中国","provinceZh":"云南省","cityZh":"临沧市","countryEn":"China","provinceEn":"YunNan","cityEn":"LinCang"}: 10,{"countryZh":"中国","provinceZh":"内蒙古自治区","cityZh":"乌海市","countryEn":"China","provinceEn":"InnerMongoliaAutonomousRegion","cityEn":"WuHai"}: 3}'
d=re.findall('.*?cityZh":"(.*?)","countryEn',s)
结果:['临沧市', '乌海市']
如果是:
d=re.findall('.*cityZh":"(.*?)","countryEn',s)
结果:[ '乌海市']
如果是:
d=re.findall('.*?cityZh":"(.*)","countryEn',s)
['临沧市","countryEn":"China","provinceEn":"YunNan","cityEn":"LinCang"}: 10,{"countryZh":"中国","provinceZh":"内蒙古自治区","cityZh":"乌海市']
3.常用函数
1.sub替换:
#替换s中的hello为123,
s = "hello,world!!!"
print(re.sub(r'hello', "123", s))
#123,world!!!