0

I want to remove the data between single quotes i.e. avcd

a = 'avcd';

I am using this code. Although, i am getting the the text data from a text file.

text = 'acbnmmff hjkki.
    It is recommended'

r = re.sub(r"= '.*?';", '', text.rstrip('\r\n'))

My code is working fine but when the text contains any newline, then it fails at the new line.

How can i make it work

5
  • Fails how? Make what work? Commented Mar 17, 2015 at 8:53
  • do you get an exception? which one? Commented Mar 17, 2015 at 8:56
  • When i try to replace the data in the text variable, then only acbnmmff hjkki. gets replaced. Similarly when i try to get the data between ' and '; then i only gets acbnmmff hjkki. not the whole string. Commented Mar 17, 2015 at 9:04
  • replace newlines with something else and put them back afterward. Commented Mar 17, 2015 at 9:05
  • If you're going to insist on using regular expressions for this, then I'm pretty sure you'll need to add the re.MULTILINE flag to your regular expression. docs.python.org/2/library/re.html#re.MULTILINE Commented Mar 17, 2015 at 9:05

2 Answers 2

1

There is the misconception that . matches everything in python. But it doesn't match new lines unless you specify the re.DOTALL flag. You can use it in your case like this:

r = re.sub(r"= '.*?';", '', text.rstrip('\r\n'), flags=re.DOTALL)
Sign up to request clarification or add additional context in comments.

Comments

0

Try this: r = re.sub(r"= '.*?';", '', text.rstrip('\r\n'), flags=re.DOTALL)

4 Comments

string to replace is unknown. It comes dynamically.
So what? For example: a is the substring to be replaced and b is the new substring (where a & b are variable). You may use it like: r = text.replace(a, b)
I dont know what is a. I just know that whatever is there between = ' and '; to be replaced with null. How the above code be used ?
Sorry, misunderstood your problem. Then you have to use regex. You can achhieve that by: r = re.sub(r"= '.*?';", '', text.rstrip('\r\n'). re.DOTALL) For matching new lines, DOTALL flag is required

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.