【问题标题】:Python dealing with string-matchingPython处理字符串匹配
【发布时间】:2015-08-17 12:42:22
【问题描述】:

有一个这样的字符串:

mystr = 'account_id 37318 not found'

我想知道如何写一个条件比:

if 'account_id' not in str and 'not found' not in str:
    doSomething()

我想一定有这样的:

if 'account_id' + %any substring% + 'not found' not in str:
   doSomething()

也许正则表达式可能会有所帮助,但我不擅长使用它。

提前谢谢你。

【问题讨论】:

  • 首先...str 是一个非常糟糕的变量名。
  • 哦,是的,当然)这只是一个例子。我会编辑

标签: python regex string-matching


【解决方案1】:

您可以使用all,但不要使用内置关键字作为变量名。

if all(i not in s for i in ('not found', 'account_id')):

例子:

>>> tr = 'account_id 37318 not found'
>>> tr1 = '2735723'
>>> all(i not in tr for i in ('not found', 'account_id'))
False
>>> all(i not in tr1 for i in ('not found', 'account_id'))
True
>>>

【讨论】:

    【解决方案2】:

    这可能会有所帮助。

    import re
    string = 'account_id 37318 not found'
    
    match = re.search(r'\baccount_id\b.*?\bnot found\b',string)
    if match:
        print 'Do something'
    else:
        print 'Do nothing'
    

    如果有帮助,请告诉我:)。

    【讨论】:

    • 使用\baccount_id\b.*?\bnot found\b 可能会更好(不需要描述字符串的开头和结尾,并且以文字字符串开头的模式总是更有效)。
    猜你喜欢
    • 2020-07-31
    • 2011-03-22
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2011-09-17
    相关资源
    最近更新 更多