正则表达式:如何匹配包含“\n”的字符串(换行)?

发布于 2024-12-16 02:16:48 字数 513 浏览 2 评论 0原文

我正在尝试使用正则表达式从 SQL 导出文件转储数据。为了匹配帖子内容的字段,我使用“(?P.*?)”。大多数情况下它工作正常,但如果该字段包含“\n”字符串,则正则表达式将不匹配。如何修改正则表达式以匹配它们?谢谢!

示例(我使用的是Python):

>>> re.findall("'(?P<content>.*?)'","'<p>something, something else</p>'")
['<p>something, something else</p>']

>>> re.findall("'(?P<content>.*?)'","'<p>something, \n something else</p>'")
[]

PS 似乎所有前面带有“\”的字符串都被视为转义字符。我如何告诉 regx 按原样对待它们?

I'm trying to dump data from a SQL export file with regular expression. To match the field of post content, I use '(?P<content>.*?)'. It works fine most of the time, but if the field contains the string of '\n' the regular expression wouldn't match. How can I modify the regular expression to match them? Thanks!

Example(I'm using Python):

>>> re.findall("'(?P<content>.*?)'","'<p>something, something else</p>'")
['<p>something, something else</p>']

>>> re.findall("'(?P<content>.*?)'","'<p>something, \n something else</p>'")
[]

P.S. Seemingly all strings with '\' in the front are treated as escape characters. How can I tell regx to treat them as they are?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

装迷糊 2024-12-23 02:16:48

您应该使用 DOTALL 选项:

>>> re.findall("'(?P<content>.*?)'","'<p>something, \n something else</p>'", re.DOTALL)
['<p>something, \n something else</p>']

请参阅 这个

You should use DOTALL option:

>>> re.findall("'(?P<content>.*?)'","'<p>something, \n something else</p>'", re.DOTALL)
['<p>something, \n something else</p>']

See this.

林空鹿饮溪 2024-12-23 02:16:48

您需要 Dotall 修饰符,以使点也匹配换行符。

re.S
重新.DOTALL
制作“.”特殊字符匹配任意字符
全部,包括换行符;没有这个标志,'.'会匹配任何东西
除了换行符。

请参阅在 docs.python.org 上

You need the Dotall modifier, to make the dot also match newline characters.

re.S
re.DOTALL
Make the '.' special character match any character at
all, including a newline; without this flag, '.' will match anything
except a newline.

See it here on docs.python.org

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文