Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.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 使用Regex获取“之后的所有用户”;用户:“;_Python_Regex - Fatal编程技术网

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

Python 使用Regex获取“之后的所有用户”;用户:“;,python,regex,Python,Regex,我有一个这种格式的文本文件 Users: user1 user2 Groups: group1 group2 我尝试使用以下模式从该列表中获取用户(user1和user2): userRegex = 'Users:\n(\s+\S+\n)*' users = re.search(userRegex, groupInfo) 但是列表是空的,我在这里缺少什么?使用 重新导入 groupInfo=“”用户: 用户1 用户2 组: 第一组 第2组“ m

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

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

userRegex = 'Users:\n(\s+\S+\n)*'
users = re.search(userRegex, groupInfo)
但是列表是空的,我在这里缺少什么?

使用

重新导入
groupInfo=“”用户:
用户1
用户2
组:
第一组
第2组“
match=re.search(r'Users:\s*(.*)(=\n组:)',groupInfo,re.s)
如果匹配:
打印(match.group(1.split())

结果
['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

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

from P4 import P4

p4 = P4()

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

如果组和用户节的顺序不同,我会将正则表达式更改为
r'Users:\s*(.*)(=\n\s+$)
。我尝试了您的解决方案,但它不起作用?我现在也在学习Regex@KamranPerviz您没有启用
re.S
re.DOTALL
,这是正确的-当您量化捕获组时,它匹配所有重复,但只捕获最后一次。