Search code examples
pythonregextext

Search all values within parenthesis by using Regex Python


I have a list of text like this format-

2021-07-11 18:34:24,381: Mouse clicked at (159, 88) with Button.left

Here, I want to search this "(159, 88)" pattern with the bracket from my entire text file.

The 1st and 2nd values in the parenthesis can be One digit to four digits. I mean this format can be (1, 888) or (20, 32) or (134, 4) or (365, 567) or (1240, 122) or (1345, 1245).

Now, by using regex, how do I solve this problem?

My expected output is- (384, 567)

Please help.


Solution

  • Use the pattern '\(\d+,\s*\d+\)' to match the substring you want.

    >>> 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)']
    

    Understanding the pattern: '\(\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