匹配 Python 中包含转义字符的两个字符串(E:() [英] Matching two strings in Python which has Escape character in it(E:()

查看:43
本文介绍了匹配 Python 中包含转义字符的两个字符串(E:()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

temp=PID ie() 调用 u 5 1n 5n T sseach=PID ie() 调用 u 5 1n 5n T ss

我试过这个:re.match(temp, each) 但它不匹配

解决方案

首先,re.match() 中的第一个参数是正则表达式,python 会将它们视为正则表达式,而正弦您在 temp 中有括号,它们将被评估为捕获组.

如果你想要一个正确的匹配,你需要逃避它们:

<预><代码>>>>temp = "PID ie\(\) 调用 u 5 1n 5n T ss">>>重新匹配(温度,每个)<_sre.SRE_Match 对象;span=(0, 46), match='PID ie() Invoked u 5 1n 5n T ss'>

或者你可以使用 re.escape() 来转义正则表达式:

<预><代码>>>>re.match(re.escape(temp), each)<_sre.SRE_Match 对象;span=(0, 46), match='PID ie() Invoked u 5 1n 5n T ss'>>>>

其次如果您只想检查相等性,您可以简单地使用 == 运算符.

temp == each

Example:

temp=PID ie()     Invoked      u   5   1n   5n T ss
each=PID ie()     Invoked      u   5   1n   5n T ss

I've tried this: re.match(temp, each) but it does not match

解决方案

First off, he first argument in re.match() is a regex and python will treat them as regex notations, and sine you have parenthesis in temp they will be evaluated as capture groups.

You need to escape them if you want a proper match:

>>> temp = "PID ie\(\)     Invoked      u   5   1n   5n T ss"
>>> re.match(temp, each)
<_sre.SRE_Match object; span=(0, 46), match='PID ie()     Invoked      u   5   1n   5n T ss'>

Or you could use re.escape() in order to escape the regex notations:

>>> re.match(re.escape(temp), each)
<_sre.SRE_Match object; span=(0, 46), match='PID ie()     Invoked      u   5   1n   5n T ss'>
>>> 

Secondly if you just want to check the equality you can simply use == operator.

temp == each

这篇关于匹配 Python 中包含转义字符的两个字符串(E:()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆