簡體   English   中英

使用正則表達式驗證部分或完整字符串

[英]Validate part or the complete string with regex

當它以單詞的特定部分開頭時,我正在嘗試匹配字符串。 很難解釋,所以我舉一個例子。 我正在研究一個腳本,該腳本檢查用戶需要在Cisco設備上使用哪種網絡接口。 它可以是以太網,FastEthernet,GigabitEthernet或TenGigabitEthernet。 事情是; 用戶可以使用縮寫指定這些名稱。 例如,字符串“ Fa”可用於FastEthernet,但也可用於“ Fas”,“ Fast”,“ FastE”等。

因此,我需要的是一個正則表達式,當用戶輸入“ Fas”或“ Fast”時,它可以為FastEthernet提供正匹配。

我嘗試了以下正則表達式;

^(Fa | Fas | Fast | FastE | FastEt | FastEth | FastEthe | FastEther | FastEthern | FastEtherne | FastEthernet)

哪個可行,但非常丑陋,並不真正可移植。

#!/usr/bin/env python3

import re

def get_interface(name):
    """ Return the full name of the interface """

    if re.match('^(Gi|Gig|Giga|Gigab|Gigabi|Gigabit|GigabitE|GigabitEt|GigabitEth|GigabitEthe|GigagibitEther|GigabitEthern|GigabitEtherne|GigabitEthernet)', name):
        return 'GigabitEthernet'
    elif re.match('^(Fa|Fas|Fast|FastE|FastEt|FastEth|FastEthe|FastEther|FastEthern|FastEtherne|FastEthernet)', name):
        return 'FastEthernet'
    elif re.match('^(Et|Eth|Ethe|Ether|Ethern|Etherne|Ethernet)', name):
        return 'Ethernet'


print(get_interface('Gi'))

沒有錯誤訊息。

實際上,這實際上不需要正則表達式,沒有正則表達式則更簡單。

當添加新的以太網變體並檢查模棱兩可和未知的名稱時,以下解決方案可以很好地擴展。

variants = ["Ethernet", "FastEthernet", "GigabitEthernet", "TenGigabitEthernet"]

def get_interface(name):
    result = None
    for v in variants:
        if v.startswith(name):
            if result:
                raise KeyError("Ambiguous name")
            result = v
    if not result:
        raise KeyError("Unknown name")
    return result

干得好:

import re

name = 'Gig'

def get_interface(name):
    options = ['GigabitEthernet', 'FastEthernet', 'Ethernet']
    for option in options:
        if any(re.match(line, name) for line in [option[0:i+1] for i in range(len(option))]):
            return option

輸出:

GigabitEthernet

暫無
暫無

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

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