Python中的正则表达式匹配

时间:2019-05-18 16:38:22

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

我想找到两个至少有一个错误的相似字符串。 我想使用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

2 个答案:

答案 0 :(得分: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<3}

答案 1 :(得分:0)

我不太确定another的方差。但是,也许我们可以添加一个中间带负向后捕捉的捕获组,并传递您想要的another并使那些不需要的捕获组失败。也许在这里,我们可以定义类似于以下内容的表达式:

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

enter image description here

RegEx

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

RegEx电路

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

enter image description here

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!
相关问题