Python正则表达式:如何匹配单词的子字符串

2024-05-13 05:40:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建正则表达式来匹配它们是否是命令的子字符串。你知道吗

示例:配置终端

匹配如果至少有:conf t

我试着用:r'conf(igure)?\s*t(erminal)?' 但它也和“conftxxx”匹配。 而且,它与“config t”不匹配

我的问题是,我想创建这样的匹配。你知道吗

匹配: 配置器 配置术语 形态t

不匹配: 配置tminal

如果匹配可选,则需要按顺序进行。你知道吗

谢谢!你知道吗


Tags: 字符串命令config终端示例顺序conf形态
3条回答

在这里详细说明@usr2564301的评论

import re pattern = r'conf(i(g(u(r(e)?)?)?)?)?\st(e(r(m(i((n(a(l)?)?)?))?)?)?)?' text='config t' print(re.match(pattern, text))

regex不是一个很好的解决方案,因为它并不特别适合这样的测试,而且它也不容易配置、维护和扩展。你知道吗

更好的方法是编写一个单独的函数来测试单个输入i与可能的匹配m,如果

  1. len(i) >= minimum_length_required,和
  2. i得到的数据与从m得到的长度匹配。你知道吗

这适用于单字条目:

def partialMatch(entry, full, minimum):
    return len(entry) >= minimum and entry == full[:len(entry)]

>>> print (partialMatch('con', 'configure', 4))
False
>>> print (partialMatch('config', 'configure', 4))
True
>>> print (partialMatch('confiture', 'configure', 4))
False

但是使用多单词命令需要更多的工作,因为每个单独的单词都必须被检查——而且,大概还有一长串可能的命令。但是,总体思路应该是这样的:

def validate(entry, cmd_list):
    entry = entry.split()
    if len(entry) != len(cmd_list):
        return False
    for index,word in enumerate(entry):
        if not partialMatch(word, cmd_list[index].replace('#',''), cmd_list[index].find('#')):
            return False
    return True

其中cmd_list包含允许条目的列表,#字符与最小条目文本的位置匹配。所以你可以

>>> print (validate ('conf', ['conf#igure', 't#erminal']))
False
>>> print (validate ('conf t', ['conf#igure', 't#erminal']))
True
>>> print (validate ('configure t', ['conf#igure', 't#erminal']))
True
>> print (validate ('conf #', ['conf#igure', 't#erminal']))
False

(当然,您通常不会将有效的命令存储在这个调用本身中,而是存储在一个较长的列表中,并在上面循环以查找有效的命令。)

这是一个例子

s="conf fxxx "
if not s.find('conf t'):
    print('yes')
else:
    print('no')

相关问题 更多 >