Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:正则表达式_Python_Regex_Strip - Fatal编程技术网

Python:正则表达式

Python:正则表达式,python,regex,strip,Python,Regex,Strip,我有以下代码,可以根据我的需要从该命令的结果中检索包名: 命令: dpkg --get-selections | grep amule 要分析的字符串: string = 'amule\t\t\t\t\t\tinstall\namule-common\t\t\t\t\tinstall\namule-utils\t\t\t\t\tinstall\n' 代码: pattern = re.compile(r"[a-z](.*)\w*(?=([\\\t]*install))") matches =

我有以下代码,可以根据我的需要从该命令的结果中检索包名:

命令:

dpkg --get-selections | grep amule
要分析的字符串:

string = 'amule\t\t\t\t\t\tinstall\namule-common\t\t\t\t\tinstall\namule-utils\t\t\t\t\tinstall\n'
代码:

pattern = re.compile(r"[a-z](.*)\w*(?=([\\\t]*install))")
matches = re.finditer(pattern, result[0])

for match in matches:
    plist.append(match.group().strip())
结果:

plist = ['amule', 'amule-common', 'amule-utils']
但是我想优化代码,不使用strip函数,只使用regex获得相同的结果。尽管如此,到目前为止,我还是无法去掉所有的'\t',甚至在'install'字符串之前使用'+'、'*'或{n}。有什么想法吗


谢谢

您应该能够通过使用
re.M
标志(多行)轻松做到这一点

“([\w\-]+)\s*安装”,re.M

像这样:

match = re.search(r"([\w\-]+)\s*install", re.M)
if match:
    plist = match

请参见此处的一个工作示例:

您应该能够通过使用
re.M
标志(多行)轻松完成此操作

“([\w\-]+)\s*安装”,re.M

像这样:

match = re.search(r"([\w\-]+)\s*install", re.M)
if match:
    plist = match
请参见此处的一个工作示例:

好的,在您的帮助下(反斜杠是问题所在),下面是我可以想到的

pattern = re.compile(r'([\w\-]+)(?=(\s*install\s*))', re.MULTILINE)
matches = re.finditer(pattern, string_to_analize)

for match in matches:
    print match.group()
这正是我们所需要的

非常感谢你的帮助!;)

PS:只是一件非常奇怪的事情:regex在网站上不起作用,你明白为什么吗

好的,在你的帮助下(反斜杠是个问题),我可以想到以下几点

pattern = re.compile(r'([\w\-]+)(?=(\s*install\s*))', re.MULTILINE)
matches = re.finditer(pattern, string_to_analize)

for match in matches:
    print match.group()
这正是我们所需要的

非常感谢你的帮助!;)


PS:只是一件非常奇怪的事情:regex在网站上不起作用,你明白为什么吗

2个信息(网站和正则表达式)在1回答:谢谢!很抱歉再次打扰您,但实际上该代码在webiste上有效,但不是像第一篇文章中那样编码的字符串。我试图用他们的界面修改它,但没有成功。到目前为止,我掌握的python代码是:p=re.compile(r'([\w\-]+)[\\t]*install[\\n]*',re.MULTILINE)str=“amule\t\t\t\t\t\t\t\t\t\t\t\t安装\n”p.match(str),它在网站上工作,但不在我的shell中。站点:这些\t实体是特殊的字符选项卡--转义它们以检索文本
\t
(您使用的是\\t,\\n)会给您带来问题。尝试删除双反斜杠?2信息(网站和正则表达式)在1回答:谢谢!很抱歉再次打扰您,但实际上该代码在webiste上有效,但不是像第一篇文章中那样编码的字符串。我试图用他们的界面修改它,但没有成功。到目前为止,我掌握的python代码是:p=re.compile(r'([\w\-]+)[\\t]*install[\\n]*',re.MULTILINE)str=“amule\t\t\t\t\t\t\t\t\t\t\t\t安装\n”p.match(str),它在网站上工作,但不在我的shell中。站点:这些\t实体是特殊的字符选项卡--转义它们以检索文本
\t
(您使用的是\\t,\\n)会给您带来问题。尝试删除双反斜杠?