簡體   English   中英

使用正則表達式創建具有正向回溯的字典列表

[英]Using regex to create a list of dictionaries with positive lookbehind

我正在嘗試使用正則表達式肯定后向創建字典列表。 我嘗試了兩種不同的代碼:

變體 1

string = '146.204.224.152 - lubo233'

for item in re.finditer( "(?P<host>[0-9]*[.][0-9]*[.][0-9]*[.][0-9]*)(?P<user_name>(?<= - )[a-z]*[0-9]*)", string ):
    print(item.groupdict())

變體 2

string = '146.204.224.152 - lubo233'
for item in re.finditer( "(?P<host>[0-9]*[.][0-9]*[.][0-9]*[.][0-9]*)(?<= - )(?P<user_name>[a-z]*[0-9]*)", string ):
    print(item.groupdict())

所需 Output

{'host': '146.204.224.152', 'user_name': 'lubo233'}

問題/問題

在這兩種情況下,我都無法消除 substring“-”。

使用積極的后視(?<= - )會使我的代碼出錯。

任何人都可以幫助確定我的錯誤嗎? 謝謝。

我建議您刪除積極的后視,並在每個部分之間正常放置連接字符

還有一些改進

  • \. 而不是[.]

  • [0-9]{,3}而不是[0-9]*

  • (?:\.[0-9]{,3}){3}而不是\.[0-9]{,3}\.[0-9]{,3}\.[0-9]{,3}

添加.*-以處理可能存在的任何單詞

rgx = re.compile(r"(?P<host>[0-9]{,3}(?:\.[0-9]{,3}){3}).* - (?P<user_name>[a-z]*[0-9]*)")

vals = ['146.204.224.152 aw0123 abc - lubo233',
        '146.204.224.152 as003443af - lubo233',
        '146.204.224.152 - lubo233']

for val in vals:
    for item in rgx.finditer(val):
        print(item.groupdict())

# Gives
{'host': '146.204.224.152', 'user_name': 'lubo233'}
{'host': '146.204.224.152', 'user_name': 'lubo233'}
{'host': '146.204.224.152', 'user_name': 'lubo233'}

積極向后看不起作用的原因是您正在嘗試匹配:

  • (?P<host>[0-9]*[.][0-9]*[.][0-9]*[.][0-9]*)一個IP 地址
  • 緊隨其后的用戶名模式(?P<user_name>(?<= - )[az]*[0-9]*)前面應該是(?<= - )

因此,一旦正則表達式引擎使用了IP 地址模式,您就會告訴它應該匹配一個以(?<= - )開頭的用戶名模式,但前面的是IP 地址模式。 換句話說,一旦匹配了IP 模式,左邊的字符串就是:

- lubo233

應該立即匹配的模式,如re.match ,是:

(?P<user_name>(?<= - )[a-z]*[0-9]*) 

那顯然不匹配。 為了說明我的觀點,請查看此模式是否有效:

import re

string = '146.204.224.152 - lubo233'
for item in re.finditer(r"((?P<host>[0-9]*[.][0-9]*[.][0-9]*[.][0-9]*)( - ))(?P<user_name>(?<= - )[a-z]*[0-9]*)", string):
    print(item.groupdict())

Output

{'host': '146.204.224.152', 'user_name': 'lubo233'}

如果您需要在兩種模式之間匹配任意數量的字符,您可以這樣做:

import re

string = '146.204.224.152 adfadfa - lubo233'
for item in re.finditer(r"((?P<host>\d{3,}[.]\d{3,}[.]\d{3,})(.* - ))(?P<user_name>(?<= - )[a-z]*[0-9]*)", string):
    print(item.groupdict())

Output

{'host': '146.204.224', 'user_name': 'lubo233'}

暫無
暫無

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

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