python - 正则表达式获取双引号之间的所有内容

标签 python regex

我试图让一个正则表达式来处理一串多行文本。需要这个才能为 python 工作。

示例文本:

description : "4.10 TCP Wrappers - not installed"
info        : "If some of the services running in /etc/inetd.conf are 

required, then it is recommended that TCP Wrappers are installed and configured to limit access to any active TCP and UDP services.

TCP Wrappers allow the administrator to control who has access to various inetd network services via source IP address controls. TCP Wrappers also provide logging information via syslog about both successful and unsuccessful connections.

TCP Wrappers are generally triggered via /etc/inetd.conf, but other options exist for \"wrappering\" non-inetd based software.

The configuration of TCP Wrappers to suit a particular environment is outside the scope of this benchmark; however the following links will provide the necessary documentation to plan an appropriate implementation:

ftp://ftp.porcupine.org/pub/security/index.html

The website contains source code for both IPv4 and IPv6 versions."

expect      : "^[\\s]*[A-Za-z0-9]+:[\\s]+[^A][^L][^L]"
required        : YES

我想出了这个,

[(a-zA-Z_ \t#)]*[:][ ]*\"[^\"]*.*\"

但问题是它停在第二个“该行的其余部分未被选中。”

我的目标是获取从信息开始到双引号结尾的整个字符串,与信息行相关。

同样的正则表达式也适用于“expect”行,从 expect 开始到与 expect 字符串相关的双引号结束。

一旦我得到整个字符串,我将在第一个“:”上拆分它,因为我想将这些字符串存储到数据库中,其中“description”、“info”、“expect”作为列,然后字符串作为值那些专栏。

感谢您的帮助!

最佳答案

一种替代方法是使用 shlex 模块中提供的词法分析器:

>>> s = """tester : "this is a long string
that
is multiline, contains \\" double qoutes \\" and .
this line is finished\""""
>>> shlex.split(s[s.find('"'):])[0]
'this is a long string\nthat\nis multiline, contains " double qoutes " and .\nthis line is finished'

它还会从字符串中的双引号中删除反斜线。

代码找到字符串中的第一个双引号,并只查看从那里开始的字符串。然后它使用 shlex.split() 标记字符串的剩余部分,并从返回的列表中取出第一个标记。

关于python - 正则表达式获取双引号之间的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28177904/

相关文章:

javascript - 在 HTML 模板中使用 Javascript 检索 Flask JSON 对象

python - 添加两个 Pandas 系列,同时将(非数字)值保持在不匹配的索引处

regex - 使用 Perl 正则表达式删除引号和撇号的所有变体

regex - 谷歌分析过滤器显示没有流量

java - Java 中的 Arcane isPrime 方法

python - 如何在 Python 中添加包含字典值的列

python - 以编程方式获取 python 函数参数的描述

Python MFC : Updating static text in response to events

regex - sed 语法,错误不匹配 ( 或\(

Java/替换所有引号