获得匹配字符串的百分比与正则表达式

时间:2018-05-04 15:03:56

标签: python regex

我需要获得与提供的字符串匹配的正则表达式的百分比,例如。我有正则表达式:

^[A-Za-z]{1,2}[0-9]{4}[a-zA-Z]{1,3}$

试图匹配包含一个或两个字符,四个数字和一到三个字符的字符串。现在,如果我将此正则表达式应用于aa1234bb,它将匹配但如果使用aa1234则不匹配。

我想要的是将正则表达式应用于字符串之后它应该返回字符串与正则表达式匹配的百分比,例如对于aa1234,它与给定的正则表达式匹配几乎70%,如果我们考虑最大值任何匹配的字符串都有10个字符。

2 个答案:

答案 0 :(得分:1)

我无法想象这对于完全一般的(即接受任何正则表达式)和完全在re内的可能性。

一种天真但可能足够的方法是二元搜索。这假定您的正则表达式始终绑定到字符串的前面。下面是一个粗略的,未经测试的例子来展示这个想法。显然,对于长字符串,它可能会执行正则表达式几次。

def percent_match(regex, target):
    left = 0
    right = len(target) - 1
    current = right // 2
    while left < right:
        if regex.match(target[left:right]):
            left = current
        else:
            right = current
        current = (right - left) // 2
    return m / len(target)

另一方面,如果你只需要使用一个正则表达式,那么@ctwheels方法可能最有意义。

答案 1 :(得分:0)

这是我的尝试:

import re
full_pattern = re.compile(r"^([a-z][a-z]?)?(\d\d\d\d)?([a-z][a-z]?[a-z]?)?$")
num_pos_matches = 3 # 9 groups in our reg

list_of_test_cases = ["aa1234bb","aa1234","1234bb","aabb","+pow","aa","1234","b5555bb"]

def get_match_percentage(in_str):
  m = re.match(full_pattern,in_str)
  if m == None:
    return 0
  m_g = m.groups()

  counter = 0
  for x in m_g:
    if x == None:
      counter+=1
  return round((1 - counter/num_pos_matches) * 100,2)

# print some tests
for test_case in list_of_test_cases:
  print(test_case, " matched ",get_match_percentage(test_case), "% of the ",num_pos_matches, " Regex groups")

输出:

aa1234bb  matched  100.0 % of the  3  Regex groups
aa1234  matched  66.67 % of the  3  Regex groups
1234bb  matched  66.67 % of the  3  Regex groups
aabb  matched  66.67 % of the  3  Regex groups
+pow  matched  0 % of the  3  Regex groups
....

我认为肯定存在一些失败的案例,例如我希望"123dfg"能够提供33.33%,但它会产生

123dfg  matched  0 % of the  3  Regex groups

所以你可以稍微按摩它来解决这些问题。对于团队的想法,很多信誉都归功于@ctwheels。