使用Regex获取“users:”之后的所有用户

2024-09-24 06:00:12 发布

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

我有一个这种格式的文本文件

Users:
      user1
      user2
Groups:
      group1
      group2

我尝试使用以下模式从该列表中获取用户(user1和user2):

userRegex = 'Users:\n(\s+\S+\n)*'
users = re.search(userRegex, groupInfo)

但是名单是空的,我还缺什么


Tags: 用户re列表search格式模式usersgroups
2条回答

使用

import re
groupInfo = """Users:
      user1
      user2
Groups:
      group1
      group2"""

match = re.search(r'Users:\s*(.*?)(?=\nGroups:)', groupInfo, re.S)
if match:
    print(match.group(1).split())

proof

结果['user1', 'user2']

正则表达式解释

                                        
  Users:                   'Users:'
                                        
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
                                        
  (                        group and capture to \1:
                                        
    .*?                      any character except \n (0 or more times
                             (matching the least amount possible))
                                        
  )                        end of \1
                                        
  (?=                      look ahead to see if there is:
                                        
    \n                       '\n' (newline)
                                        
    Groups:                  'Groups:'
                                        
  )                        end of look-ahead

如果您使用P4Python,我假设这是一个Perforce组规范,当您获取一个组时,它会自动将规范解析为一个Python对象,因此不需要正则表达式

from P4 import P4

p4 = P4()

p4.connect()
group = p4.fetch_group("mygroup")
users = group['Users']
subgroups = group['Groups']
p4.disconnect()

相关问题 更多 >