使用re模块

时间:2019-03-17 11:05:18

标签: python

如何使用re模块复制文本文件中以特定单词开头和结尾的重复段落并将每个段落插入列表的索引中

段落示例

RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_140116/cleanup/stat_KSHA500 --conf /export/home-V cisco -N -S -o -P telnet,ssh2
RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_140200/cleanup/stat_KSHA11 --conf /export/home-V cisco -N -S -o -P telnet,ssh2
RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_1500/cleanup/stat_KSHA211 --conf /export/home-V cisco -N -S -o -P telnet,ssh2

1 个答案:

答案 0 :(得分:0)

撇开语言障碍,根据您的条件尝试

>>> import re

>>> string = '''RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_140116/cleanup/stat_KSHA500 --conf /export/home-V cisco -N -S -o -P telnet,ssh2
RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_140200/cleanup/stat_KSHA11 --conf /export/home-V cisco -N -S -o -P telnet,ssh2
RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_1500/cleanup/stat_KSHA211 --conf /export/home-V cisco -N -S -o -P telnet,ssh2'''


>>> configs = re.findall('(?i)RemoteConfig[\S\s]*?ssh2(?=\s|$)', string)


>>> for config in configs:
        print(config)

#Output
RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_140116/cleanup/stat_KSHA500 --conf /export/home-V cisco -N -S -o -P telnet,ssh2
RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_140200/cleanup/stat_KSHA11 --conf /export/home-V cisco -N -S -o -P telnet,ssh2
RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_1500/cleanup/stat_KSHA211 --conf /export/home-V cisco -N -S -o -P telnet,ssh2




>>> configs

#Output
['RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_140116/cleanup/stat_KSHA500 --conf /export/home-V cisco -N -S -o -P telnet,ssh2', 'RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_140200/cleanup/stat_KSHA11 --conf /export/home-V cisco -N -S -o -P telnet,ssh2', 'RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_1500/cleanup/stat_KSHA211 --conf /export/home-V cisco -N -S -o -P telnet,ssh2']