Try this:

import re
w = "TEMPLATES = ( ('index.html', 'home'), ('base.html', 'base'))"

# find outer parens
outer = re.compile("\((.+)\)")
m = outer.search(w)
inner_str = m.group(1)

# find inner pairs
innerre = re.compile("\('([^']+)', '([^']+)'\)")

results = innerre.findall(inner_str)
for x,y in results:
    print("%s <-> %s" % (x,y))

Output:

index.html <-> home
base.html <-> base

Explanation:

outer matches the first-starting group of parentheses using \( and \); by default search finds the longest match, giving us the outermost ( ) pair. The match m contains exactly what's between those outer parentheses; its content corresponds to the .+ bit of outer.

innerre matches exactly one of your ('a', 'b') pairs, again using \( and \) to match the content parens in your input string, and using two groups inside the ' ' to match the strings inside of those single quotes.

Then, we use findall (rather than search or match) to get all matches for innerre (rather than just one). At this point results is a list of pairs, as demonstrated by the print loop.

Update: To match the whole thing, you could try something like this:

rx = re.compile("^TEMPLATES = \(.+\)")
rx.match(w)
Answer from phooji on Stack Overflow
Top answer
1 of 5
42

Try this:

import re
w = "TEMPLATES = ( ('index.html', 'home'), ('base.html', 'base'))"

# find outer parens
outer = re.compile("\((.+)\)")
m = outer.search(w)
inner_str = m.group(1)

# find inner pairs
innerre = re.compile("\('([^']+)', '([^']+)'\)")

results = innerre.findall(inner_str)
for x,y in results:
    print("%s <-> %s" % (x,y))

Output:

index.html <-> home
base.html <-> base

Explanation:

outer matches the first-starting group of parentheses using \( and \); by default search finds the longest match, giving us the outermost ( ) pair. The match m contains exactly what's between those outer parentheses; its content corresponds to the .+ bit of outer.

innerre matches exactly one of your ('a', 'b') pairs, again using \( and \) to match the content parens in your input string, and using two groups inside the ' ' to match the strings inside of those single quotes.

Then, we use findall (rather than search or match) to get all matches for innerre (rather than just one). At this point results is a list of pairs, as demonstrated by the print loop.

Update: To match the whole thing, you could try something like this:

rx = re.compile("^TEMPLATES = \(.+\)")
rx.match(w)
2 of 5
18

First of all, using \( isn't enough to match a parenthesis. Python normally reacts to some escape sequences in its strings, which is why it interprets \( as simple (. You would either have to write \\( or use a raw string, e.g. r'\(' or r"\(".

Second, when you use re.match, you are anchoring the regex search to the start of the string. If you want to look for the pattern anywhere in the string, use re.search.

Like Joseph said in his answer, it's not exactly clear what you want to find. For example:

string = "TEMPLATES = ( ('index.html', 'home'), ('base.html', 'base'))"
print re.findall(r'\([^()]*\)', string)

will print

["('index.html', 'home')", "('base.html', 'base')"]

EDIT:

I stand corrected, @phooji is right: escaping is irrelevant in this specific case. But re.match vs. re.search or re.findall is still important.

๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ library โ€บ re.html
re โ€” Regular expression operations โ€” Python 3.14.7 ...
Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has been performed, and can be matched later in the string with the \number special ...
Discussions

regex: match everything inside brackets including other brackets
The ? in .*? makes it non-greedy - meaning it will take the shortest match. Removing the ? means it is greedy - and will take the longest match. >>> re.search("(\((.*)\))", expr).group(1) '(x3, (x0, x1, x2))' But if you have any further ) in your data - it will "break" - it doesn't match the corresponding closing paren. It looks like you're trying to write a tokenizer. There are better tools for this though e.g. pyparsing. More on reddit.com
๐ŸŒ r/learnpython
1
2
January 25, 2023
Python: How to match nested parentheses with regex? - Stack Overflow
There is a new regular engine module being prepared to replace the existing one in Python. It introduces a lot of new functionality, including recursive calls. Copyimport regex s = 'aaa(((1+0)+1)+1)bbb' result = regex.search(r''' (? #capturing group rec \( #open parenthesis (?: #non-capturing ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Can regex (python) check if a supplied equation has all the matching open and closed parenthesis?
to be pedantic, this is not solvable using regular expressions alone. some tools such as recursive regex can help in specific scenarios, but to implement something that works in all scenarios you need a parser (matching parenthesis is a matter for context-free grammar, not regex) More on reddit.com
๐ŸŒ r/learnprogramming
13
3
March 22, 2021
Python: regex matching anything inside parentheses (also other parentheses) - Stack Overflow
I'm working with python and regex and I'm trying to transform a string like the following: (1694439,805577453641105408,'\"@Bessemerband not reverse gear simply pointing out that I didn\'t say wha... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
DevGenius
blog.devgenius.io โ€บ regex-parentheses-examples-of-every-type-aba8441be761
Regex Parentheses: Examples of Every Type | by Tyler J Funk | Dev Genius
October 19, 2020 - This is the type of parentheses that I personally knew nothing about before researching them, and I think this is probably true for other regex beginners like myself. Non-capturing groups essentially do the same thing as capturing groups, except, as it sounds, we do not โ€œcaptureโ€ the pattern between the parentheses. If we donโ€™t add the g flag, and use the .match method, weโ€™ll get back an array like the one in the example directly above, but we donโ€™t get the capture group at index [1] and so on, simply the full match at index [0], and we still have the same capability of using .index and .input like the example directly above.
๐ŸŒ
YouTube
youtube.com โ€บ watch
python regex match parentheses - YouTube
Download this code from https://codegive.com Regular expressions (regex) are powerful tools for pattern matching in strings. In this tutorial, we'll focus on...
Published: January 19, 2024
๐ŸŒ
py4u
py4u.org โ€บ blog โ€บ python-regex-matching-a-parenthesis-within-parenthesis
Python Regex: How to Match Parentheses Within Parentheses (Practical Example Guide)
Python's built-in re module does not support recursive patterns. However, the third-party regex library (a drop-in replacement for re) supports recursion using (?R) (shorthand for "recurse the entire pattern") or (?&groupname) (recurse a named group). This works for simple to moderately nested structures. The core pattern for matching balanced parentheses with recursion is:
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ python regex to return string between parentheses
Python Regex to Return String Between Parentheses - Be on the Right Side of Change
June 19, 2022 - The '\( ... \)' part matches the opening and closing parentheses. You need to escape the parentheses characters to tell the regex engine that you donโ€™t want it to assume itโ€™s a regex group operation that also starts with parentheses. import re s = '(Learn Python) (not C++)' result = ...
๐ŸŒ
Quora
quora.com โ€บ What-is-the-role-of-parenthesis-in-Pythons-regular-expressions
What is the role of parenthesis in Python's regular expressions? - Quora
Answer: Role of Parenthesis in Regex Use Parentheses for Grouping and Capturing By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together. This allows you to apply a quantifier to the entire group or to restrict alte...
Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ regex: match everything inside brackets including other brackets
r/learnpython on Reddit: regex: match everything inside brackets including other brackets
January 25, 2023 -

Hi there,

I'm trying to match the inside of the most "external" brackets i.e. from Sum(x3, (x0, x1, x2)) I'd like to extract Sum(x3, (x0, x1, x2)).

I tried

import re
expr = "Sum(x3, (x0, x1, x2))"
match = re.search("(\((.*?)\))", expr) 
bracket_part = match.group(1)
print(bracket_part)

yet this matches only Sum(x3, (x0, x1, x2). Of course one could simply add a ) yet it would be nice to extract (x) from expression like sin(x).

Do guys have an idea how to tell regex to match up until the very last closing bracket? Thanks a lot in advance!

๐ŸŒ
Electronic Clinic
electroniclinic.com โ€บ python-regular-expressions-or-regex-matching-searching-replacing
Python Regular Expressions or regex Matching, Searching, Replacing
April 4, 2021 - For example, โ€˜\nโ€™ is a single ... in easier to read expressions. ... Description โ†’ Matches whatever regular expression pattern is inside the parentheses and causes that part of the matched substring to be remembered....
๐ŸŒ
Iditect
iditect.com โ€บ faq โ€บ python โ€บ python-regex-matching-a-parenthesis-within-parenthesis.html
Python regex: matching a parenthesis within parenthesis
To match a parenthesis within parenthesis using regular expressions in Python, you can use regex capture groups to define and capture the nested parentheses.
๐ŸŒ
Regular-Expressions.info
regular-expressions.info โ€บ brackets.html
Regex Tutorial: Parentheses for Grouping and Capturing
It stores the part of the string matched by the part of the regular expression inside the parentheses. The regex Set(Value)? matches Set or SetValue. In the first case, the first (and only) capturing group remains empty. In the second case, the first capturing group matches Value.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ can regex (python) check if a supplied equation has all the matching open and closed parenthesis?
r/learnprogramming on Reddit: Can regex (python) check if a supplied equation has all the matching open and closed parenthesis?
March 22, 2021 -

I wrote regex to validate the syntax of an equation, but I can't get it to fail if all open parenthesis aren't closed. I currently have the parenthesis check as an IF statement before I run the regex check, but I'd like to incorporate that validation in the regex.

I checked out using capture groups and referencing them with look behinds, but can't seem to find enough information about how to use them.

Is there a way for regex to have a conditional, like a closed parenthesis is required here if an open parenthesis was used in an earlier spot?

Here's my regex that works for all the test equations I threw at it:

(I'm sure the regex is junk, and could be vastly improved. I just slapped it together today)

valid_result = re.fullmatch(
r'((\(\s)*([0-9]*\s|\.[0-9]*\s|[0-9]*\.[0-9]*\s|\.[0-9]*\s)'
r'((\+|\-|\*|\/|\**)\s)'
r'([0-9]*\s?|\.[0-9]*\s?|[0-9]*\.[0-9]*\s?|\.[0-9]*\s?)(\s\))*?'
r'((\+|\-|\*|\/|\**)\s)?)+', self.equation
)

I want to reference the first bold section (match an open parenthesis) in the second bold section (closed parenthesis) to verify if I need a closing parenthesis there. Or vice versa.

Any help would be appreciated. Thanks.

edit: I couldn't bold inline code without messing up the code. So nothing is bold.

The open parenthesis is the first thing matched on the 1st line, the closed parenthesis is matched at the end of the 3rd line.

๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 44634302 โ€บ python-regex-matching-anything-inside-parentheses-also-other-parentheses
Python: regex matching anything inside parentheses (also other parentheses) - Stack Overflow
If your string can also contain parenthesis not enclosed between quotes, you can solve the problem using a recursive pattern with the regex module (using it and the csv module is a good idea) or building a state machine.
๐ŸŒ
Python
docs.python.org โ€บ 3.4 โ€บ library โ€บ re.html
6.2. re โ€” Regular expression operations โ€” Python 3.4.10 documentation
June 16, 2019 - Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has been performed, and can be matched later in the string with the \number special sequence, described below.
๐ŸŒ
SciPython
scipython.com โ€บ blog โ€บ parenthesis-matching-in-python
Parenthesis matching in Python
def check_parentheses(s): """ Return True if the parentheses in string s match, otherwise False. """ j = 0 for c in s: if c == ')': j -= 1 if j < 0: return False elif c == '(': j += 1 return j == 0 def find_parentheses(s): """ Find and return the location of the matching parentheses pairs in s.
๐ŸŒ
Reddit
reddit.com โ€บ r/regex โ€บ how do i match only the first parentheses?
r/regex on Reddit: How do I match only the first parentheses?
July 12, 2022 -

I have a text of following pattern.

9) Find the angle between (12:00 to 11:59) the hour hand and the minute hand of a clock.

10) Find the last non-zero digit of the factorial of 1234.

11) Check if a given number is nearly prime or not. A nearly prime number is a positive integer that is equal to the product of two prime numbers.

I want to match the ")" after the numbers in the beginning.

How can I do that. I am using Python.

๐ŸŒ
Iditect
iditect.com โ€บ faq โ€บ python โ€บ python-how-to-match-nested-parentheses-with-regex.html
Python: How to match nested parentheses with regex?
Matching nested parentheses using regular expressions in Python can be challenging because regular expressions are not well-suited for handling nested structures. However, you can use recursive patterns in Python's re module to achieve this.