【问题标题】:In Python, how to write a regular expression matching strings starting with string A but NOT ending with B在 Python 中,如何编写一个正则表达式匹配以字符串 A 开头但不以 B 结尾的字符串
【发布时间】:2016-09-23 18:28:43
【问题描述】:

我有一些字符串,例如:

tool_abc
tool_abc_data
tool_xyz
tool_xyz_data
file_abc
file_xyz_data

我的目标是有一个正则表达式来匹配任何以tool_ 开头且不以_data 结尾的字符串。怎么写?

【问题讨论】:

标签: python regex


【解决方案1】:

来自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_.*$(?&lt;!_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')

【讨论】:

    【解决方案2】:

    也许是这样的?:

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

    【讨论】:

      猜你喜欢
      • 2022-08-03
      • 1970-01-01
      • 2016-12-07
      • 2015-04-27
      • 1970-01-01
      • 1970-01-01
      • 2019-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多