1

How can I search for a text and if matched delete the entire line, preferably in regex.

What I have tried so far:

My file:

wait                    => '10',

Trial one

data = re.sub(r"^.*wait.*$","",data) #does not work

Trial two:

data = re.sub(r".+/wait/.+","",data) #does not work

1 Answer 1

4

Your regexp is not correct. Try this:

import re
print re.sub(".*wait.*\n",'',"""wait                    => '10',
wait                    => '10',
Other data
wait                    => '10',
""",flags=re.M)


http://docs.python.org/2/library/re.html#re.M

re.M

re.MULTILINE

When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline); and the pattern character '$' matches at the end of the string and at the end of each line (immediately preceding each newline). By default, '^' matches only at the beginning of the string, and '$' only at the end of the string and immediately before the newline (if any) at the end of the string.

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

6 Comments

I fixed it. Sorry. Let me know if you need more clarification. Thanks! (the * in my re was not being parsed by SO.. had to escape it)
Yea, if your on OSX then Patterns kicks butt! itunes.apple.com/us/app/patterns-the-regex-app/…
Sorry, not aware of. But you can try regexpal.com I have not used it myself, but it may work well for you.
@enginefree: The above re.sub() call is incorrect: the 4th argument is count, not flags. Also you don't need flags=re.M unless you use patterns ^ or $ that are affected by it. Mere re.sub(r".*wait.*\n?", "", data) works because '.' doesn't match a newline without re.S flag.
Nice catch my friend. Updated.
|

Your Answer

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