Python理解正则表达式

2024-09-28 19:23:22 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我从学校的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'

Tags: 代码importre列表informationmatch错误stdout
2条回答

问题是,当match方法与任何内容都不匹配时,它不会返回空的match对象,您可以在该对象上调用group方法,它会返回None。它没有group方法。在调用任何方法之前,只需检查None。你知道吗

#lookup
import re
p = re.compile(r'j(?!j)\w*')
result = p.match(str(information))
if result:
    print result.group()

^{}的文档中:

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding match object. Return None if the string does not match the pattern;

re.match仅当匹配从字符串的开头开始时才有用,它不会在字符串中找到所有匹配项。你知道吗

剩下两个主要选项:

  • 按行拆分输入文件并使用re.match

  • 使用多行匹配和re.findall

选项1:

r = subprocess.Popen(['ls', '/home/administrator/sotest'], stdout=subprocess.PIPE)
information = r.stdout.read().decode('utf-8').split('\n') # ['ajax2', 'jaxe32', 'jjape3', '']

for user in information:
    s = re.match(r'j(?!j)\w*', user)
    if s:
        print(s.group())

输出:

jaxe32

选项2(使用^{}):

r = subprocess.Popen(['ls', '/home/administrator/sotest'], stdout=subprocess.PIPE)
information = r.stdout.read().decode('utf-8') # 'ajax2\njaxe32\njjape3\n'

print(re.findall(r'(?m)^j(?!j)\w*$', information))

输出:

['jaxe32']

相关问题 更多 >