在Python中,如何编写匹配以字符串A开头但不以B结尾的字符串的正则表达式

时间:2016-05-25 23:23:58

标签: python regex

我有一些字符串:

tool_abc
tool_abc_data
tool_xyz
tool_xyz_data
file_abc
file_xyz_data

我的目标是让RegEx匹配以tool_开头且不以_data结尾的任何字符串。我怎么写一个?

2 个答案:

答案 0 :(得分:2)

来自https://docs.python.org/2/library/re.html#regular-expression-syntax

(?<!...)
Matches if the current position in the string is not preceded by a match
for .... This is called a negative lookbehind assertion. Similar to positive 
lookbehind assertions, the contained pattern must only match strings of some
fixed length and shouldn’t contain group references. Patterns which start
with negative lookbehind assertions may match at the beginning of the string
being searched..

我认为你需要的正则表达式是'^tool_.*$(?<!_data)'

>>> re.match('^tool_.*$(?<!_data)', 'tool_abc')
<_sre.SRE_Match object at 0x10ef4fd98>
>>> re.match('^tool_.*$(?<!_data)', 'tool_abc_data')
>>> re.match('^tool_.*$(?<!_data)', 'tool_abc_data_file')
<_sre.SRE_Match object at 0x10ef4fe00>
>>> re.match('^tool_.*$(?<!_data)', 'tool_abc_file')
<_sre.SRE_Match object at 0x10ef4fd98>
>>> re.match('^tool_.*$(?<!_data)', 'tool_abc_data')
>>> re.match('^tool_.*$(?<!_data)', 'abc_data')
>>> re.match('^tool_.*$(?<!_data)', 'file_xyz_data')
>>> re.match('^tool_.*$(?<!_data)', 'file_xyz')

答案 1 :(得分:1)

也许是这样的?:

strStart = "tool_"
strEnd = "_data"

for s in Strings_list:
    if s.startswith(strStart) and not s.endswith(strEnd):
        doSomething()
    else:
        doSomethingElse()