168
u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'

All I need is the contents inside the parenthesis.

2
  • 5
    Why not use double quotes? It would make the string easier to read, i.e. u"abcde(date='2/xc2/xb2',time='/case/test.png')"
    – kzh
    Feb 4, 2011 at 3:01
  • 1
    This question makes me nervous just looking at it. I get the sneaking suspicion OP really wants the functionality in ast and just doesn't know it exists.
    – Kevin
    Feb 13, 2015 at 2:10

11 Answers 11

364

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

s[s.find("(")+1:s.find(")")]
4
  • 18
    what if there is no '(' and ')'? you will get s[0:-1]. Which means you will get whatever in 's' :\. It will be good if you check that the string has parenthesis first.
    – Omar
    May 26, 2016 at 1:21
  • 6
    What if you'll have "(some text (some text in inner parenthesis) some more text)"? Jul 13, 2016 at 12:17
  • 14
    Then the problem is not as simple as the original problem and will require a different solution.
    – tkerwin
    Jul 13, 2016 at 17:26
  • 2
    For Igor's question: if you have nested parenthesis like that, you use rfind for the second part of the operation. See my post below for more details on this.
    – FaustoW
    Feb 17, 2017 at 20:48
96

Use re.search(r'\((.*?)\)',s).group(1):

>>> import re
>>> s = u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'
>>> re.search(r'\((.*?)\)',s).group(1)
u"date='2/xc2/xb2',time='/case/test.png'"
0
81

If you want to find all occurences:

>>> re.findall('\(.*?\)',s)
[u"(date='2/xc2/xb2',time='/case/test.png')", u'(eee)']

>>> re.findall('\((.*?)\)',s)
[u"date='2/xc2/xb2',time='/case/test.png'", u'eee']
4
  • 3
    might be a stupid question, but why is the "?" needed ? Why does "(.*)" not work?
    – CutePoison
    May 29, 2019 at 10:07
  • 16
    @CutePoison because .* is greedy (will take the longest match) and .*? is not greedy (will take the shortest match)
    – dopstar
    Jun 15, 2019 at 16:21
  • THANK YOU! Probably the best answer all night! Apr 7, 2021 at 3:33
  • 1
    this does not work.... you have to add .* before and after like r".*((.*?)).*"
    – zdanman
    Jan 22, 2022 at 21:58
38

Building on tkerwin's answer, if you happen to have nested parentheses like in

st = "sum((a+b)/(c+d))"

his answer will not work if you need to take everything between the first opening parenthesis and the last closing parenthesis to get (a+b)/(c+d), because find searches from the left of the string, and would stop at the first closing parenthesis.

To fix that, you need to use rfind for the second part of the operation, so it would become

st[st.find("(")+1:st.rfind(")")]
1
  • 2
    @ALH that expression does not have nested parenthesis, which is what my answer is good for.
    – FaustoW
    Dec 23, 2019 at 20:51
10
import re

fancy = u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'

print re.compile( "\((.*)\)" ).search( fancy ).group( 1 )
7
contents_re = re.match(r'[^\(]*\((?P<contents>[^\(]+)\)', data)
if contents_re:
    print(contents_re.groupdict()['contents'])
2
  • 2
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value Jan 22, 2020 at 6:14
  • This worked like a charm including newline. Thanks for the solution.
    – Sunil
    Jun 9, 2022 at 17:41
5

No need to use regex .... Just use list slicing ...

string="(tidtkdgkxkxlgxlhxl) ¥£%#_¥#_¥#_¥#"
print(string[string.find("(")+1:string.find(")")])
1
  • 6
    This was already posted over 9 years ago. Dec 10, 2020 at 6:19
2

TheSoulkiller's answer is great. just in my case, I needed to handle extra parentheses and only extract the word inside the parentheses. a very small change would solve the problem

>>> s=u'abcde((((a+b))))-((a*b))'
>>> re.findall('\((.*?)\)',s)
['(((a+b', '(a*b']
>>> re.findall('\(+(.*?)\)',s)
['a+b', 'a*b']
1

Here are several ways to extract strings between parentheses in Pandas with the \(([^()]+)\) regex (see its online demo) that matches

  • \( - a ( char
  • ([^()]+) - then captures into Group 1 any one or more chars other than ( and )
  • \) - a ) char.

Extracting the first occurrence using Series.str.extract:

import pandas as pd
df = pd.DataFrame({'Description':['some text (value 1) and (value 2)']})
df['Values'] = df['Description'].str.extract(r'\(([^()]+)\)')
# => df['Values']
#    0    value 1
#    Name: Values, dtype: object

Extracting (finding) all occurrences using Series.str.findall:

import pandas as pd
df = pd.DataFrame({'Description':['some text (value 1) and (value 2)']})
df['Values'] = df['Description'].str.findall(r'\(([^()]+)\)')
# => df['Values']
#    0    [value 1, value 2]
#    Name: Values, dtype: object

df['Values'] = df['Description'].str.findall(r'\(([^()]+)\)').str.join(', ')
# => df['Values']
#    0    value 1, value 2
#    Name: Values, dtype: object

Note that .str.join(', ') is used to create a comma-separated string out of the resulting list of strings. You may adjust this separator for your scenario.

0

If im not missing something, a small fix to @tkerwin: s[s.find("(")+1:s.rfind(")")]

The 2nd find should be rfind so you start search from end of string

-1

testcase

s = "(rein<unint>(pBuf) +fsizeof(LOG_RECH))"

result

['pBuf', 'LOG_RECH', 'rein<unint>(pBuf) +fsizeof(LOG_RECH)']

implement

def getParenthesesList(s):
    res = list()
    left = list()
    for i in range(len(s)):
        if s[i] == '(':
            left.append(i)
        if s[i] == ')':
            le = left.pop()
            res.append(s[le + 1:i])
    print(res)
    return res

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.