![](/img/trans.png)
[英]How to match words in 2 list against another string of words without sub-string matching in Python?
[英]Python Regex: How to match sub string of words
我想创建正则表达式以匹配它们是否是命令的子字符串。
示例:配置终端
至少匹配:conf t
我尝试使用: r'conf(igure)?\\s*t(erminal)?'
但它也匹配“ conf txxxxx”之类的东西。 此外,它与“ config t”不匹配
我的问题是我想创建与此类匹配的对象。
匹配:配置程序配置术语配置
不匹配:配置终端
如果匹配可选,则需要按顺序排列。
谢谢!
正则表达式不是一个很好的解决方案,因为它并不特别适合于这种测试,而且也不容易配置,维护和扩展。
更好的方法是编写一个单独的函数,针对可能的匹配m
测试单个输入i
,如果满足,则返回True
len(i) >= minimum_length_required
,并且 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')
只是在这里详述@ 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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.