【问题标题】:Regular expression matching in Python [duplicate]Python中的正则表达式匹配[重复]
【发布时间】:2019-05-18 16:38:22
【问题描述】:

我想找到两个至少有一个错误的相似字符串。 我想使用re库中内置的python。

例子

import re

re.match(r"anoother","another") #this is None indeed

它应该返回 True 并检查它是否有一个或两个拼写错误。

我已经寻找了很长的重新文档 但是我不知道当有一种类型时如何使用这些知识

a="this is the anoother line\n"
b="this is the another line\n"
c=re.search(r"{}".format(a),b) #how to write regex code here? 
#c =True  #it should return True

我希望返回True

re.any_regex_func(r"anyregex this is anoother line anyregex","this is another line")

如果它有多个类型,则返回 false

【问题讨论】:

  • 我不认为正则表达式是正确的工具。您可以尝试查看确定编辑距离的算法。
  • Google 类似“python 模糊字符串匹配”之类的东西,正则表达式可能不是您要找的。​​span>
  • 在标准库中有用于此类任务的“difflib”模块。
  • 好的。我是正则表达式的新手,这就是为什么我问它是否可能。我可以在没有正则表达式的情况下编写算法。
  • 谢谢大家!我将搜索另一个库

标签: python regex regex-lookarounds regex-group regex-greedy


【解决方案1】:

您要查找的内容称为模糊匹配,但遗憾的是 re 模块不提供此功能。

但是pypi/regex模块有它并且易于使用(您可以设置模式中一个组允许的字符插入、删除、替换和错误的数量)。示例:

>>> import regex
>>> regex.match(r'(?:anoother){d}', 'another')
<regex.Match object; span=(0, 7), match='another', fuzzy_counts=(0, 0, 1)>

{d} 允许删除非捕获组,但您可以设置允许写入的最大值,例如 {d&lt;3}

【讨论】:

    【解决方案2】:

    我不太确定another 的差异。但是,也许我们可以添加一个带有负面后视的中间捕获组,并通过您想要的anothers 并让那些不想要的那些失败。也许,在这里我们可以定义我们的表达式,类似于:

    ^((.+?)(another?|anoother?)(.+))$
    

    正则表达式

    如果这不是您想要的表达方式,您可以在regex101.com 中修改/更改您的表达方式。

    正则表达式电路

    您还可以在jex.im 中可视化您的表达式:

    Python 演示

    # -*- coding: UTF-8 -*-
    import re
    
    string = "this is the other line\n"
    expression = r'^((.+?)(another?|anoother?)(.+))$'
    match = re.search(expression, string)
    if match:
        print("YAAAY! \"" + match.group(1) + "\" is a match ??? ")
    else: 
        print('? Sorry! No matches!')
    

    输出

    ? Sorry! No matches!
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      相关资源
      最近更新 更多