[英]Python Regex match a mac address from the end?
我有以下重新提取MAC地址:
re.sub( r'(\S{2,2})(?!$)\s*', r'\1:', '0x0000000000aa bb ccdd ee ff' )
但是,這給了我0x:00:00:00:00:00:aa:bb:cc:dd:ee:ff
。
如何在從最后開始匹配前6對之后修改此正則表達式,以便得到aa:bb:cc:dd:ee:ff
?
注意:字符串之間有空格,可以忽略。 只需要最后12個字符。
Edit1: re.findall( r'(\\S{2})\\s*(\\S{2})\\s*(\\S{2})\\s*(\\S{2})\\s*(\\S{2})\\s*(\\S{2})\\s*$',a)
查找字符串中的最后6對。 我仍然不知道如何壓縮這個正則表達式。 同樣,這仍然取決於字符串成對的事實。
理想情況下,正則表達式應該從最后開始使用最后12個有效的\\S
字符並將它們串起來:
編輯2:靈感來自@Mariano的答案很有效,但取決於最后12個字符必須從一對開始的事實我想出了以下解決方案。 這是kludgy但似乎仍然適用於所有輸入。
string = '0x0000000000a abb ccddeeff'
':'.join( ''.join( i ) for i in re.findall( '(\S)\s*(\S)(?!(?:\s*\S\s*{11})',' string) )
'aa:bb:cc:dd:ee:ff'
編輯3: @Mariano更新了他的答案,現在適用於所有輸入
這將適用於最后12個字符,忽略空格。
碼:
import re
text = "0x0000000000aa bb ccdd ee ff"
result = re.sub( r'.*?(?!(?:\s*\S){13})(\S)\s*(\S)', r':\1\2', text)[1:]
print(result)
輸出:
aa:bb:cc:dd:ee:ff
正則表達式細分:
此代碼中使用的表達式使用re.sub()
替換主題文本中的以下內容:
.*? # consume the subject text as few as possible
(?!(?:\s*\S){13}) # CONDITION: Can't be followed by 13 chars
# so it can only start matching when there are 12 to $
(\S)\s*(\S) # Capture a char in group 1, next char in group 2
#
# The match is replaced with :\1\2
# For this example, re.sub() returns ":aa:bb:cc:dd:ee:ff"
# We'll then apply [1:] to the returned value to discard the leading ":"
您可以使用re.finditer
查找所有對,然后加入結果:
>>> my_string='0x0000000000aa bb ccdd ee ff'
>>> ':'.join([i.group() for i in re.finditer( r'([a-z])\1+',my_string )])
'aa:bb:cc:dd:ee:ff'
你可能喜歡這樣,
>>> import re
>>> s = '0x0000000000aa bb ccdd ee ff'
>>> re.sub(r'(?!^)\s*(?=(?:\s*[a-z]{2})+$)', ':', re.sub(r'.*?((?:\s*[a-z]){12})\s*$', r'\1', s ))
'aa:bb:cc:dd:ee:ff'
>>> s = '???767aa bb ccdd ee ff'
>>> re.sub(r'(?!^)\s*(?=(?:\s*[a-z]{2})+$)', ':', re.sub(r'.*?((?:\s*[a-z]){12})\s*$', r'\1', s ))
'aa:bb:cc:dd:ee:ff'
>>> s = '???767aa bb ccdd eeff '
>>> re.sub(r'(?!^)\s*(?=(?:\s*[a-z]{2})+$)', ':', re.sub(r'.*?((?:\s*[a-z]){12})\s*$', r'\1', s ))
'aa:bb:cc:dd:ee:ff'
我知道這不是你問題的直接答案,但你真的需要一個正則表達式嗎? 如果您的格式是固定的,這也應該有效:
>>> s = '0x0000000000aa bb ccdd ee ff'
>>> ':'.join([s[-16:-8].replace(' ', ':'), s[-8:].replace(' ', ':')])
'aa:bb:cc:dd:ee:ff'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.