正则表达式模式匹配字符串

时间:2015-08-21 03:26:46

标签: python regex python-2.7

匹配以abc-def-xyz开头并以任何结尾的字符串的正则表达式模式是什么?

1 个答案:

答案 0 :(得分:1)

<强>更新

由于您只想匹配以abc-def开头的主机名,因此您只需使用str.startswith()

hosts = ['abc-def.1.desktop.rul.com',
         'abc-def.2.desktop.rul.com',
         'abc-def.3.desktop.rul.com',
         'abc-def.4.desktop.rul.com',
         'abc-def.44.desktop.rul.com',
         'abc-def.100.desktop.rul.com',
         'qwe-rty.100.desktop.rul.com',
         'z.100.desktop.rul.com',
         '192.168.1.10',
         'abc-def.100abc.desktop.rul.com']
filtered_hosts = [host for host in hosts if host.startswith('abc-def')]
print filtered_hosts

<强>输出

['abc-def.1.desktop.rul.com', 'abc-def.2.desktop.rul.com', 'abc-def.3.desktop.rul.com', 'abc-def.4.desktop.rul.com', 'abc-def.44.desktop.rul.com', 'abc-def.100.desktop.rul.com', 'abc-def.100abc.desktop.rul.com']

原始的正则表达式解决方案如下。

我们假设您的数据是主机名列表,例如:

hosts = ['abc-def.1.desktop.rul.com',
         'abc-def.2.desktop.rul.com',
         'abc-def.3.desktop.rul.com',
         'abc-def.4.desktop.rul.com',
         'abc-def.44.desktop.rul.com',
         'abc-def.100.desktop.rul.com',
         'qwe-rty.100.desktop.rul.com',
         'z.100.desktop.rul.com',
         '192.168.1.10',
         'abc-def.100abc.desktop.rul.com']

import re

pattern = re.compile(r'abc-def\.\d+\.')
filtered_hosts = [host for host in hosts if pattern.match(host)]
print filtered_hosts

<强>输出

['abc-def.1.desktop.rul.com', 'abc-def.2.desktop.rul.com', 'abc-def.3.desktop.rul.com', 'abc-def.4.desktop.rul.com', 'abc-def.44.desktop.rul.com', 'abc-def.100.desktop.rul.com']

正则表达式模式表示匹配任何以abc-def.开头,后跟一个或多个数字,后跟一个点的行。

如果你想匹配一个更通用的模式,比如任何3个小写字母的序列,然后是-,然后是另外3个小写字母,你可以这样做:

pattern = re.compile(r'[a-z]{3}-[a-z]{3}\.\d+\.')

现在输出还包括'qwe-rty.100.desktop.rul.com'