【问题标题】:Capture a regex in a if condition在 if 条件下捕获正则表达式
【发布时间】:2018-07-11 01:49:33
【问题描述】:

我想在我的 if 条件下直接捕获我的正则表达式的匹配。我知道这在 PHP 中是可能的,但我不知道如何以 Pythonic 方式进行。 所以我跑了两次,一点也不性感……

str = 'Test string 178-126-587-0 with a match'
if re.findall(r'[0-9]{3}-[0-9]{3}-[0-9]{3}-[0-9]', str) != []:
    match = re.findall(r'[0-9]{3}-[0-9]{3}-[0-9]{3}-[0-9]', str)[0]

【问题讨论】:

  • 所以你只需要第一场比赛?

标签: python regex match


【解决方案1】:

在 Python 中使用条件构造时不能进行内联变量赋值,您需要利用临时变量。在您的情况下,re.search 无论如何都会采取第一个元素并且没有捕获的组:

match_ = re.search(r'[0-9]{3}-[0-9]{3}-[0-9]{3}-[0-9]', str_)
if match_:
    match = match_.group()

关于你原来的例子,空列表在 Python 中是错误的,所以:

if not some_list:
    # Do stuffs

会的。

【讨论】:

  • 感谢 heemayl,但我没有得到“.group()”的东西。为什么不匹配 [0] ,因为使用 search() 只有一个匹配项?
  • @Maxime 与re.findall 不同,re.search 返回匹配对象,而不是列表。见docs.python.org/3/library/re.html#match-objects
【解决方案2】:

我找到了这个解决方案,:= 运算符读取this post

str = 'Test string 178-126-587-0 with a match'
if (match := re.search(r'[0-9]{3}-[0-9]{3}-[0-9]{3}-[0-9]', str)):
    match = match.group()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    相关资源
    最近更新 更多