Python 正则表达式仅匹配部分括号

标签 python regex

我有一些格式不正确的文本需要过滤。因此,在很多情况下,文本中的引述从一行开始,然后被截断并在第二行结束。在这种情况下,我的偏好是完全删除部分引号,但是,我想保留常规的完整引号。我知道这可以通过计数器迭代完成,但我真的更愿意使用正则表达式。

举个例子:

"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|$) 请注意,它失败了在两种情况下:

  1. 第 3 行 -- 部分引用引述句子的其余部分(这种情况非常罕见,所以如果我们不能解决它也不是世界末日)。
  2. 第 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

DEMO

>>> 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|)

DEMO

关于Python 正则表达式仅匹配部分括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27654097/

相关文章:

python - 将值添加到数据框的所有行

python - 如何与外部Python进程通信? (不是子进程)

正则表达式匹配条件字符串

java - (?!a){0} 是什么?在 Java 正则表达式中是什么意思?

regex - grep regex 前瞻或字符串开始(或后视或字符串结尾)

python - re模块中的groups和groups有什么区别?

python - 是否可以通过 ctypes 通过引用传递 python 字符串?

python - 如何使模型的属性仅适用于user.is_staff?

python - 排除以特定字符开头的列表元素的最pythonic方法是什么?

javascript - 用连字符替换空格,但不在逗号周围替换空格