【问题标题】:Search all values within parenthesis by using Regex Python使用 Regex Python 搜索括号内的所有值
【发布时间】:2021-10-05 23:01:01
【问题描述】:

我有一个类似这种格式的文本列表-

2021-07-11 18:34:24,381:鼠标在 (159, 88) 处单击 Button.left

在这里,我想用整个文本文件中的括号搜索这个“(159, 88)”模式。

括号中的第一个和第二个值可以是一位到四位。我的意思是这种格式可以是 (1, 888) 或 (20, 32) 或 (134, 4) 或 (365, 567) 或 (1240, 122) 或 (1345, 1245)。

现在,通过使用正则表达式,我该如何解决这个问题?

我的预期输出是 - (384, 567)

请帮忙。

【问题讨论】:

    标签: python regex text


    【解决方案1】:

    使用模式'\(\d+,\s*\d+\)' 来匹配你想要的子字符串。

    >>> import re
    >>> text = '2021-07-11 18:34:24,381: Mouse clicked at (159, 88) with Button.left'
    >>> re.findall('\(\d+,\s*\d+\)', text)
    ['(159, 88)']
    

    了解模式:'\(\d+,\s*\d+\)'

    \(    : Look for opening parenthesis, \ is used as escape character
    
    \d+   : Look for one or more digits
    
    ,     : Look for exactly one comma
    
    \s*   : Zero or more white space characters
    
    \d+   : Look for one or more digits again
    
    \)    : Look for closing parenthesis, \ is used as escape character
    

    【讨论】:

    • 非常感谢。它工作正常。另一个帮助将不胜感激。我想将此输出附加到一个文本文件中,但我不知道如何用新行附加它。你能帮我解决这个问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-09
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多