1

How can i use regex in python to detect in one file only the stings between the brackets? So If i have some text like this:

</seg>
<src>Sono stati riportati casi di (sgomberi forzati) e violazioni dei diritti umani da parte della polizia, ma su scala minore rispetto agli anni precedenti.</src>

and I want to detect only (sgomberi forzati)

I use the

for line  in file.readlines():
    m=re.compile('\((.*?)\)', re.DOTALL).findall(line)
    print m

but it does not print what I need: it prints also brackets empty like this

[]
[u'sgomberi forzati']
6
  • "but it does not return what I need". Makes sense. It's not returning anything because you don't have a return statement anywhere in your code. If you mean "It doesn't print what I need": it works for me. Unless you want it to print something other than ['regional economies', 'transportation']? Please describe what kind of output you expect. Commented Apr 28, 2014 at 12:22
  • yes, It doesn't print what I need Commented Apr 28, 2014 at 12:28
  • Please describe what kind of output you expect. Commented Apr 28, 2014 at 12:30
  • what I need is the srings between the brackets, i.e (regional economies), (transportation). Commented Apr 28, 2014 at 12:33
  • Yes, and that is exactly what is being printed. So you don't actually have a problem, then? Commented Apr 28, 2014 at 12:34

1 Answer 1

1

Escape your () as follows:

m = re.compile('\((.*?)\)', re.DOTALL).findall(line)

Sign up to request clarification or add additional context in comments.

2 Comments

@user3573552, Wait a minute, I swear you just had '((.*?))'. You are someone else changed your code. o.O
The slashes were present but not visible in the first version of the code. When it was put in code blocks, they appeared.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.