从正则表达式匹配的字符串中删除换行符
我有一个如下字符串:
Financial strain: No\n?Food insecurity:\nWorry: No\nInability: No\n?Transportation needs:\nMedical: No\nNon-medical: No\nTobacco Use\n?Smoking status: Never Smoker\n?
我想首先匹配感兴趣的子字符串/句子(即以“Food insecurity”开头并以“\n?”结尾的句子),然后删除该句子中除最后一个之外的所有换行符即问号之前的那个。
我已经能够将没有最后一个换行符和问号的句子与正则表达式 (Food insecurity:).*?(?=\\n\?)
匹配,但我很难删除第一个匹配句子的 2 个换行符并返回整个预处理字符串。有什么建议吗?
I have a string as below:
Financial strain: No\n?Food insecurity:\nWorry: No\nInability: No\n?Transportation needs:\nMedical: No\nNon-medical: No\nTobacco Use\n?Smoking status: Never Smoker\n?
I want to first match the substring/sentence of interest (I.e. the sentence beginning with "Food insecurity" and ending with "\n?") then remove all the newlines in this sentence apart from the last one i.e. the one before the question mark.
I have been able to match the sentence w/o its last newline and question mark with regex (Food insecurity:).*?(?=\\n\?)
but I struggle to remove the first 2 newlines of the matched sentence and return the whole preprocessed string. Any advice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将
re.sub
与回调函数一起使用:You could use
re.sub
with a callback function: