簡體   English   中英

使用正則表達式獲取“用戶:”之后的所有用戶

[英]Using Regex to get all users after "Users:"

我有一個這種格式的文本文件。

Users:
      user1
      user2
Groups:
      group1
      group2

我正在嘗試使用此模式從此列表中獲取用戶(user1 和 user2):

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

但是列表是空的,我在這里錯過了什么?

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())

證明

結果['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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM