所以,我从学校的Linux服务器上取了一个用户名列表,上面的代码打开了保存它们的目录,并将其保存为信息
#!/usr/bin/env python
import subprocess, sys
r = subprocess.Popen(['ls','/home/ADILSTU'], stdout=subprocess.PIPE)
information = r.stdout.read()
print information, str(information)
很好用,把用户列成这样。。。每行1个。(至少有100个用户名)
ajax2
jjape3
jaxe32
我的问题是,我想为这些用户名创建一个“查找”,这是我用来搜索只以字母j开头的用户名的代码(因此应该只从这个列表中列出jaxe32)
#lookup
import re
p = re.compile(r'j(?!j)\w*')
print p.match(str(information)).group()
但是当我运行这个时,我得到了这个错误,如果我去掉了.group(),它只会说“无”,但没有错误。所以我不确定这个列表是否正确地保存到了一个字符串中,或者我只是遗漏了一些明显的东西。我只想对此使用正则表达式,而不是其他任何东西。你知道吗
Traceback (most recent call last):
File "getInformation.py", line 11, in <module>
print p.match(str(information)).group()
AttributeError: 'NoneType' object has no attribute 'group'
问题是,当
match
方法与任何内容都不匹配时,它不会返回空的match
对象,您可以在该对象上调用group
方法,它会返回None
。它没有group
方法。在调用任何方法之前,只需检查None
。你知道吗从^{} 的文档中:
re.match
仅当匹配从字符串的开头开始时才有用,它不会在字符串中找到所有匹配项。你知道吗剩下两个主要选项:
按行拆分输入文件并使用
re.match
使用多行匹配和
re.findall
选项1:
输出:
选项2(使用^{} ):
输出:
相关问题 更多 >
编程相关推荐