在python中,如何从具有给定起始和结束模式的字符串中删除某些行?
在下面的字符串中,我必须删除以日期开头、以工作注释结尾的行在python中,如何从具有给定起始和结束模式的字符串中删除某些行?,python,regex,python-3.x,Python,Regex,Python 3.x,在下面的字符串中,我必须删除以日期开头、以工作注释结尾的行 input_String= "22/01/2020 - aman singh (Work notes) Two roads diverged in a yellow wood, And sorry I could not travel both And be one traveler, long I stood 21/01/2020 - tom cruise (Work notes) And looked down one as fa
input_String= "22/01/2020 - aman singh (Work notes)
Two roads diverged in a yellow wood,
And sorry I could not travel both
And be one traveler, long I stood
21/01/2020 - tom cruise (Work notes)
And looked down one as far as I could
To where it bent in the undergrowth.
23/01/2020 - tom cruse (Work notes)
Then took the other, as just as fair
And having perhaps the better claim."
输出字符串=
Two roads diverged in a yellow wood,
And sorry I could not travel both
And be one traveler, long I stood
And looked down one as far as I could
To where it bent in the undergrowth.
Then took the other, as just as fair
And having perhaps the better claim.
您可以使用替换线
import re
pat = re.compile(r'^\d{2}/\d{2}\/\d{4}.+\(Work notes\)\n', flags=re.M)
# Match from date pattern at start of line to (Work notes) at the end
print(pat.sub('', input_String)) # replace that line with empty string
你试过什么?什么不起作用?你得到了什么?你期待什么?什么对你的代码不起作用?它在哪里?这是一个相当简单的问题,但我想知道你尝试了什么,在你提供答案之前绊倒在哪里。请考虑解释一下你的代码背后的内容。@卡莱斯蒂尼准备好了。
import re
input_String= '''22/01/2020 - aman singh (Work notes)
Two roads diverged in a yellow wood,
And sorry I could not travel both
And be one traveler, long I stood
21/01/2020 - tom cruise (Work notes)
And looked down one as far as I could
To where it bent in the undergrowth.
23/01/2020 - tom cruse (Work notes)
Then took the other, as just as fair
And having perhaps the better claim.'''
temp = re.compile(r'\d{2}/\d{2}/\d{4} - [a-zA-Z ]+ \(Work notes\)\n') # saving template of regex
string = temp.sub('', input_String) # replacing regex template in string to ''
print(string)