正则表达式找到字符串并删除整行

时间:2023-01-14 19:26:43

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 个解决方案

#1


3  

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

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

re.M

re.M被

re.MULTILINE

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.

指定时,模式字符'^'匹配字符串的开头和每行的开头(紧跟在每个换行符之后);模式字符'$'在字符串的末尾和每行的末尾(紧接在每个换行符之前)匹配。默认情况下,'^'仅匹配字符串的开头,'$'仅匹配字符串的结尾,紧接在字符串末尾的换行符(如果有)之前。

#1


3  

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

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

re.M

re.M被

re.MULTILINE

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.

指定时,模式字符'^'匹配字符串的开头和每行的开头(紧跟在每个换行符之后);模式字符'$'在字符串的末尾和每行的末尾(紧接在每个换行符之前)匹配。默认情况下,'^'仅匹配字符串的开头,'$'仅匹配字符串的结尾,紧接在字符串末尾的换行符(如果有)之前。