我有一些格式不正确的文本需要过滤。因此,在很多情况下,文本中的引述从一行开始,然后被截断并在第二行结束。在这种情况下,我的偏好是完全删除部分引号,但是,我想保留常规的完整引号。我知道这可以通过计数器迭代完成,但我真的更愿意使用正则表达式。
举个例子:
"This is a quote" This is an end "partial- quote" Here is more text. This is an end "partial- quote w/o more text" This is an "embedded" quote
Here是我当前尝试的示例 (\"[^\"\n]+?|^[^\"\n]+?\")(\n|$)
请注意,它失败了在两种情况下:
- 第 3 行 -- 部分引用引述句子的其余部分(这种情况非常罕见,所以如果我们不能解决它也不是世界末日)。
- 第 6 行 -- 嵌入引号。这是一个主要问题,也是我对我的问题采取 SO 的主要原因。它将嵌入式引号中的最后一个引号抓取到行尾。
我想我可以设置一个 if 语句并运行每一行,检查它是否少于两个引号,然后继续解析部分引号,但我认为 SO 的头脑会有一个更清晰的解决方案。
注意 所需的输出是:
"This is a quote" This is an end Here is more text. This is an end This is an "embedded" quote
(我稍后处理空格)
最佳答案
给你,
^((?:[^"\n]*"[^"\n]*")*[^"\n]*)"[^"\n]*\n[^"\n]*"(\n|)
将匹配到的字符替换为\1\n
>>> import re
>>> s = '''"This is a quote"
This is an end "partial-
quote" Here is more text.
This is an end "partial-
quote w/o more text"
This is an "embedded" quote'''
>>> m = re.sub(r'(?m)^((?:[^"\n]*"[^"\n]*")*[^"\n]*)"[^"\n]*\n[^"\n]*"(\n|)', r'\1\n', s)
>>> print(m)
"This is a quote"
This is an end
Here is more text.
This is an end
This is an "embedded" quote
如果您想处理双引号之间的多行,请使用此正则表达式。
^((?:[^"\n]*"[^"\n]*")*[^"\n]*)"(?:[^"\n]*\n)+[^"\n]*"(\n|)
关于Python 正则表达式仅匹配部分括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27654097/