简体   繁体   English

在 Python 中查找最长匹配前缀

[英]Finding longest matching prefix in Python

I have to check if a line starts with options as ["<", "<=", ">", ">=", "=="].我必须检查一行是否以选项开头 ["<", "<=", ">", ">=", "=="]。 I have tried:我试过了:

line = "<=5"
my_option = ["<", "<=", ">", ">=", "=="]
for op in my_option:
    if line.startswith(op):
       print(op)

Doing so, I get both "<" and "<=" as output but I am interested in only output "<=".这样做,我得到了“<”和“<=”作为输出,但我只对输出“<=”感兴趣。

Re order the list, so that items that are prefixes of others are later, and break after first match:重新排序列表,以便作为其他前缀的项目在后,并在第一次匹配后中断:

line = "<=5"
my_option = ["<=", ">=", "==", ">", "<"]
for op in my_option:
    if line.startswith(op):
       print(op)
       break

In that manner, the line first matched against <= and we get out the loop.以这种方式,该行首先与<=匹配,然后我们退出循环。

We can get the longest matching prefix using regex.我们可以使用正则表达式获得longest matching prefix Make my_options a set and search prefix in it like the following:使my_options成为一个set并在其中搜索前缀,如下所示:

import re

my_option = {"<", "<=", ">", ">=", "=="}
line = "<=5"

prefix = re.split(r'(-?\d*\.?\d+)', line)[0]

if prefix in my_option:
    print(prefix)

The above code would split line with a regex that matches float or integer numbers with an optional minus sign.上面的代码将用一个正则表达式分割line ,该正则表达式匹配带有可选减号的浮点数或整数。 To match a negative or positive number having exponent, replace the above regex with:要匹配具有指数的负数或正数,请将上述正则表达式替换为:

r'([+-]?\d*\.?\d+(?:[eE][-+]?\d+)?)'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM