0

I did a coding to get to print ext inside (" and within ") but i get the errors.

I mean ,if i have text: hello everyone("Can you see"), then it has to print as Can you see

My coding:

>>> import re
>>> s = "<_io.TextIOWrapper ('C:/Python34/abcd.txt') mode='w' encoding='cp1252'>"
>>> m = re.search(r"(?<=\('\=\')[^\']*", s)
>>> m.group()

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    m.group()
AttributeError: 'NoneType' object has no attribute 'group'
2
  • Your description says you need to find (", but your code has (' instead. Should you be looking for one or the other, or both? Commented Aug 10, 2014 at 3:42
  • 1
    @TheSoundDefense yes my description was unmentioned and i need to display for both! Commented Aug 10, 2014 at 3:51

4 Answers 4

1

Modify your lookbehind a little:

(?<=\(')[^']*

and you'll have the following result:

>>> m = re.search( r"(?<=\(')[^']*", s)
>>> m.group()
'C:/Python34/abcd.txt'

To be able to match both ' and " as you mention in the comment, you'd need to create another capture group (for back referencing):

(?<=\((['"]))(.*?)\1

and thus:

>>> m = re.search( r"(?<=\(([\"']))(.*?)\1", s)
>>> m.group()
"C:/Python34/abcd.txt'"
>>> m.group(1)
"'"
>>> m.group(2)
'C:/Python34/abcd.txt'
Sign up to request clarification or add additional context in comments.

1 Comment

how can i use it for both (" ") and (' ') ?,and i only need to print the text without codes!
1

Try something like this, which will use either single or double quotes. The group(1) gives the inner string. This regex escapes the outer parens so they don't represent a grouping.

>>> m = re.search(r"\(['\"](.+)?['\"]\)", s)
>>> m.group(0)
"('C:/Python34/abcd.txt')"
>>> m.group(1)
'C:/Python34/abcd.txt'
>>> m.group(1)

Comments

1

Try this simple regex: ('.*?'). It does a non-greedy search for everything enclosed in quotes.

import re
s = "<_io.TextIOWrapper ('C:/Python34/abcd.txt') mode='w' encoding='cp1252'>"
regex = re.compile(r"('.*?')")
m = regex.search(s)
m.group()

It produces this output:

"'C:/Python34/abcd.txt'"

You can also go with re.VERBOSE regexes and groupdict:

import re
s = "<_io.TextIOWrapper ('C:/Python34/abcd.txt') mode='w' encoding='cp1252'>"
regex = re.compile(r"""
    \(
    (?P<quoted>'.*?')
    \)
""", re.VERBOSE)
m = regex.search(s)
m.groupdict()["quoted"]

Comments

1

this regexp will do it:

m = re.search(r"(?<=\()[^\)]*", s)

Comments

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.