If your problem is really just this simple, you don't need regex:

s[s.find("(")+1:s.find(")")]
Answer from tkerwin on Stack Overflow
🌐
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 - And can we find all occurrences in case there are multiple such strings? Yes. Regex to the rescue! To find all strings between two parentheses, call the re.findall() function and pass the pattern '\(.*?\)' as a first argument and the string to be searched as a second argument.
Discussions

regex - python - Return Text Between Parenthesis - Stack Overflow
this returns (W,) for me, not all text within parentheses in the string. 2014-12-02T23:13:12.857Z+00:00 ... Find the answer to your question by asking. More on stackoverflow.com
🌐 stackoverflow.com
December 3, 2014
Extract string within parentheses - PYTHON - Stack Overflow
I have a string "Name(something)" and I am trying to extract the portion of the string within the parentheses! Iv'e tried the following solutions but don't seem to be getting the results I'm look... More on stackoverflow.com
🌐 stackoverflow.com
December 12, 2017
Extract text between parentheses
How do I only show dynamic texts between parentheses? for example, Mcdonalds (MCD) I want to only display MCD, and not the whole text. More on forum.bubble.io
🌐 forum.bubble.io
18
0
July 20, 2020
python - Find something between parentheses - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
🌐
Quora
quora.com › How-do-I-extract-text-within-brackets-in-Python
How to extract text within brackets in Python - Quora
Answer (1 of 5): x here is your string holding value which is (text) , to extract only text without the opening and closing brackets you need to use slicing in the starting integer in slicing we use find function to locate the index number of the opening bracket ; we add 1 to it because we want ...
🌐
Webdevelopmentscripts
webdevelopmentscripts.com › 67-get-string-between-parentheses-or-brackets
Get string between parentheses or brackets | Web development scripts
This regular expression can be applied in any programming language / scripts like php, javascript,java,perl,python,c#,asp etc. ... /(([^)]+))/ / - Start of the expression ( - Match the starting bracket. This bracket escaped with back slash as ...
🌐
GeeksforGeeks
geeksforgeeks.org › python-extract-substrings-between-brackets
Extract substrings between brackets - Python - GeeksforGeeks
January 11, 2025 - Sometimes, while working with Python strings, we can have a problem in which we require to extract all the elements of string except those which present in a substring. This is quite common problem and has application in many domains including those of day-day and competitive programming. Lets discu ... Python provides a powerful and flexible module called re for working with regular expressions. Regular expressions (regex) are a sequence of characters that define a search pattern, and they can be incredibly useful for extracting substrings from strings.
🌐
Bubble
forum.bubble.io › questions
Extract text between parentheses - Questions - Bubble Forum
July 20, 2020 - How do I only show dynamic texts between parentheses? for example, Mcdonalds (MCD) I want to only display MCD, and not the whole text.
Find elsewhere
🌐
pythontutorials
pythontutorials.net › blog › regular-expression-to-return-text-between-parenthesis
How to Use Regular Expressions to Extract Text Between Parentheses: A Practical Guide with Examples — pythontutorials.net
Document your regex with comments (e.g., # Extracts text between non-escaped parentheses). Avoid regex for complex nesting—use a parser (e.g., pyparsing in Python) for highly nested structures.
🌐
Regex Tester
regextester.com › 102866
Between parentheses - Regex Tester/Debugger
Regular Expression to RegEx to match stuff between parentheses
🌐
Stack Overflow
stackoverflow.com › questions › 27824685 › extracting-text-from-a-string-between-multiple-sets-of-parentheses-in-python
Extracting text from a string between multiple sets of parentheses in python - Stack Overflow
January 8, 2015 - import re regexp_pattern = '\([^\(\r\n]*\)' st = "Firstname Lastname ([email protected]) Firstname2 Lastname2 ([email protected])" a = re.findall(regexp_pattern, st) #this gives you the list ['([email protected])','([email protected])'] b = ''.join(a)[1:-1] #this gives you the string '[email protected])([email protected]' b.replace(")(", ",") #this gives you the string '[email protected],[email protected]' Of course, you can do it shorter if you like that more (I do): import re regexp_pattern = '\([^\(\r\n]*\)' st = "Firstname Lastname ([email protected]) Firstname2 Lastname2 ([email protected])" ''.join(re.findall(regexp_pattern, st))[1:-1].replace(")(", ",") ... Sign up to request clarification or add additional context in comments. ... you can tell Python what you'd like to split() on by passing an argument.
Top answer
1 of 3
8
string = "Will Ferrell (Nick Halsey), Rebecca Hall (Samantha), Michael Pena (Frank Garcia)"

import re
pat = re.compile(r'([^(]+)\s*\(([^)]+)\)\s*(?:,\s*|$)')

lst = [(t[0].strip(), t[1].strip()) for t in pat.findall(string)]

The compiled pattern is a bit tricky. It's a raw string, to make the backslashes less insane. What it means is: start a match group; match anything that isn't a '(' character, any number of times as long as it is at least once; close the match group; match a literal '(' character; start another match group; match anything that isn't a ')' character, any number of times as long as it is at least once; close the match group; match a literal ')' character; then match any white space (including none); then something really tricky. The really tricky part is a grouping that doesn't form a match group. Instead of starting with '(' and ending with ')' it starts with "(?:" and then again ends with ')'. I used this grouping so I could put a vertical bar in to allow two alternate patterns: either a comma matches followed by any amount of white space, or else the end of the line was reached (the '$' character).

Then I used pat.findall() to find all the places within string that the pattern matches; it automatically returns tuples. I put that in a list comprehension and called .strip() on each item to clean off white space.

Of course, we can just make the regular expression even more complicated and have it return names that already have white space stripped off. The regular expression gets really hairy, though, so we will use one of the coolest features in Python regular expressions: "verbose" mode, where you can sprawl a pattern across many lines and put comments as you like. We are using a raw triple-quote string so the backslashes are convenient and the multiple lines are convenient. Here you go:

import re
s_pat = r'''
\s*  # any amount of white space
([^( \t]  # start match group; match one char that is not a '(' or space or tab
[^(]*  # match any number of non '(' characters
[^( \t])  # match one char that is not a '(' or space or tab; close match group
\s*  # any amount of white space
\(  # match an actual required '(' char (not in any match group)
\s*  # any amount of white space
([^) \t]  # start match group; match one char that is not a ')' or space or tab
[^)]*  # match any number of non ')' characters
[^) \t])  # match one char that is not a ')' or space or tab; close match group
\s*  # any amount of white space
\) # match an actual required ')' char (not in any match group)
\s*  # any amount of white space
(?:,|$)  # non-match group: either a comma or the end of a line
'''
pat = re.compile(s_pat, re.VERBOSE)

lst = pat.findall(string)

Man, that really wasn't worth the effort.

Also, the above preserves the white space inside the names. You could easily normalize the white space, to make sure it is 100% consistent, by splitting on white space and rejoining with spaces.

string = '  Will   Ferrell  ( Nick\tHalsey ) , Rebecca Hall (Samantha), Michael\fPena (Frank Garcia)'

import re
pat = re.compile(r'([^(]+)\s*\(([^)]+)\)\s*(?:,\s*|$)')

def nws(s):
    """normalize white space.  Replaces all runs of white space by a single space."""
    return " ".join(w for w in s.split())

lst = [tuple(nws(item) for item in t) for t in pat.findall(string)]

print lst # prints: [('Will Ferrell', 'Nick Halsey'), ('Rebecca Hall', 'Samantha'), ('Michael Pena', 'Frank Garcia')]

Now the string has silly white space: multiple spaces, a tab, and even a form feed ("\f") in it. The above cleans it up so that names are separated by a single space.

2 of 3
3

A good place for regular expressions:

>>> import re
>>> pat = "([^,\(]*)\((.*?)\)"
>>> re.findall(pat, "Will Ferrell (Nick Halsey), Rebecca Hall (Samantha), Michael Pena (Frank Garcia)")
[('Will Ferrell ', 'Nick Halsey'), (' Rebecca Hall ', 'Samantha'), (' Michael Pena ', 'Frank Garcia')]
🌐
Alteryx Community
community.alteryx.com › t5 › Alteryx-Designer-Desktop-Discussions › Extracting-Data-from-Inside-a-Parentheses › td-p › 549933
Solved: Extracting Data from Inside a Parentheses - Alteryx Community
April 29, 2024 - here is a Regex to achieve it. It's a bit tricky because you have to escape the parenthesis and use them in order to catch it. ... Workflow attached. Let me know if it works for you! ... I took a different approach, I used text to columns and used the ( as my delimiter. Then I used a formula to remove the other ) and that would just leave me with the text inside the parentheses.
Top answer
1 of 2
3

I think your problem is that your .* operators are being greedy - they will consume as much as they can if you don't put a ? after them: .*?. Also, note that since you want the parentheses, you shouldn't need the lookahead/lookbehind operations; they will exclude the parentheses they find.

Instead of fully debugging your regex, I decided to just rewrite it:

>>> import re
>>> foo ='((peach W/O juice) OR apple OR (pear W/O water) OR kiwi OR (lychee AND sugar) OR (pineapple W/O salt))'
>>> regex = '\([a-zA-Z ]*?W/O.*?\)'
>>> re.findall(regex, foo)
['(peach W/O juice)', '(pear W/O water)', '(pineapple W/O salt)']

Here's the breakdown:

\( captures the leading parentheses - note that it's escaped

[a-zA-Z ] captures all alphabetical characters and a space (note the space after Z before the closing bracket) I used this instead of . so that no other parentheses will be captured. Using the period operator would cause (lychee AND sugar) OR (pineapple W/O salt) to be captured as one match.

*? the * causes the characters in the bracket to match 0 or more times, but the ? says to only capture as many as you need to make a match

W/O captures the "W/O" that you're looking for

.*? captures any more characters (again, non-greedy because of ?)

\) captures the trailing parenthesese

2 of 2
1

Since you want to include parenthesis in the result, you don't need to use lookarounds. You can use a character class that exclude the closing parenthesis. In this way, you are sure that W/O is between parenthesis:

re.findall(r'\([^()]* W/O [^)]*\)', foo)
🌐
Microsoft Power Platform Community
powerusers.microsoft.com › t5 › Building-Power-Apps › regex-to-extract-inside-parentheses › td-p › 1317480
Forums | Microsoft Power Platform Community
June 17, 2024 - Find the answers you need in forums, at events, and across user groups—all available in one Power Platform Community.
🌐
Stack Overflow
stackoverflow.com › questions › 48881713 › regex-python-to-get-string-between-parenthesis
regex: python to get string between parenthesis - Stack Overflow
I need to fetch text between parenthesis { text } in python. here is my sample string, my_txt = "/home/admin/test_dir/SAM_8860-fg_frame_{001,002,003,004,005,007}.png" I need numbers between {}. I...