re模块
1.sub(pattern, repl, string, count=0, flags=0)
:
-
pattern:为正则表达式的模式字符串
-
repl:被替换成的内容
-
string:需要被替换的内容
-
count:由于可以匹配多个值,这里选定匹配的个数,0表示所有
-
flags:表示匹配的模式
返回值:string中被替换以后的字符串
2.flags可选参数如下:
简写 | 全名 | 注释 |
---|---|---|
I | IGNORECASE | 忽略大小写 |
M | MULTILINE | 多行模式 |
S | DOTALL | 检查包括换行符在内的所有字符 |
L | LOCALE | 使预定字符类 \w \W \b \B \s \S 取决于当前区域设定 |
U | UNICODE | 使预定字符类 \w \W \b \B \s \S \d \D 取决于unicode定义的字符属性 |
X | VERBOSE | 详细模式。该模式下正则表达式可以是多行,忽略空白字符,并可以加入注释 |
3.例子:
import re
config = '!\n\rversion 12.2\n\rservice timestamps debug uptime\n\rservice timestamps log uptime\n\rno service password-encryption\n!\nhostname PE1\n\r!\nboot-start-marker\nboot-end-marker\n!\n!\nno aaa new-model\nip subnet-zero\nip source-route\n!\n!\n!\n!\nip cef\nno ip domain lookup\n!\n!\nmultilink bundle-name authenticated\nno mpls traffic-eng auto-bw timers\nmpls label range 100 199\ncall rsvp-sync\n!\n!\n!\n!\n!\n!\n!\n!\n!\npseudowire-class EoMPLS\n encapsulation mpls\n!\n!\n!\n!\n!\n!\n!\ninterface Loopback0\n ip address 1.1.1.1 255.255.255.255\n no clns route-cache\n!\ninterface FastEthernet0/0\n description ***connect to CE1 ethernet Port****\n no ip address\n speed auto\n duplex half\n no clns route-cache\nxconnect 2.2.2.2 100 pw-class EoMPLS\n!\ninterface FastEthernet0/1\n no ip address\n shutdown\n speed auto\n duplex auto\n!\ninterface Serial1/0\n description ***connect to P***\n ip address 150.1.13.1 255.255.255.0\n mpls ip\n serial restart-delay 0\n no clns route-cache\n!\ninterface Serial1/1\n no ip address\n shutdown\n serial restart-delay 0\n no clns route-cache\n!\ninterface Serial1/2\n no ip address\n shutdown\n serial restart-delay 0\n no clns route-cache\n!\ninterface Serial1/3\n no ip address\n shutdown\n serial restart-delay 0\n no clns route-cache\n!\ninterface FastEthernet2/0\n no ip address\n speed auto\n duplex auto\n no cdp enable\n no clns route-cache\n!\ninterface FastEthernet2/0.110\n encapsulation dot1Q 110\n xconnect 2.2.2.2 110 pw-class EoMPLS\n!\ninterface FastEthernet2/1\n no ip address\n shutdown\n speed auto\nduplex auto\nno clns route-cache\n!\nrouter ospf 1\n router-id 1.1.1.1\n log-adjacency-changes\n network 1.1.1.1 0.0.0.0 area 0\n network 150.1.13.1 0.0.0.0 area 0\n!\nip classless\n!\n!\nno ip http server\nno ip http secure-server\n!\n!\n!\n!\ncontrol-plane\n!\n!\ndial-peer cor custom\n!\n!\n!\n!\ngatekeeper\n shutdown\n!\n!\nline con 0\n exec-timeout 0 0\n logging synchronous\n stopbits 1\nline aux 0\n stopbits 1\nline vty 0 4\nno login\n!\nend\n\rquitshut\n'
# 将字符串中的'\r'删除
config = re.sub('\r', '', config, flags=re.DOTALL)
# 将字符串顶部的'version 12.2'删除
config = re.sub('version /d*./d*', '', config, flags=re.DOTALL)
# 将字符串底部的'end'后的所有字符删除
config = re.sub('\nend.*', '\nend', config, flags=re.DOTALL)
print config