[英]Generating regex string to be used in re.match()
I am trying to a string to be used as regex String.我正在尝试将字符串用作正则表达式字符串。
In the following code:在以下代码中:
_pattern
is a pattern like abba
and I am trying to check _string
follows the _pattern
(eg. catdogdogcat
) _pattern
是一种类似于abba
的模式,我正在尝试检查_string
遵循_pattern
(例如catdogdogcat
)
rxp
in the following code is the regular expression that I am trying to create to match to _string
(eg. for above example it will be (.+)(.+)\\\\2\\\\1
).以下代码中的
rxp
是我试图创建以匹配_string
的正则表达式(例如,对于上面的示例,它将是(.+)(.+)\\\\2\\\\1
)。 Which is being successfully generated.正在成功生成。 But the
re.match()
is returning None
.但是
re.match()
正在返回None
。
I want to understand why it is not working and how to correct it ?我想了解为什么它不起作用以及如何纠正它?
import re
_pattern = "abba" #raw_input().strip()
_string = "catdogdogcat" #raw_input().strip()
hm = {}
rxp = ""
c = 1
for x in _pattern:
if hm.has_key(x):
rxp += hm[x]
continue
else:
rxp += "(.+)"
hm[x]="\\\\"+str(c)
c+=1
print rxp
#print re.match(rxp,_string) -> (Tried) Not working
#print re.match(r'rxp', _string) -> (Tried) Not working
print re.match(r'%s' %rxp, _string) # (Tried) Not working
Output输出
(.+)(.+)\\\\2\\\\1 None
Expected Output预期产出
(.+)(.+)\\\\2\\\\1 <_sre.SRE_Match object at 0x000000000278FE88>
The thing is that your regex string variable has double \\\\
instead of a single one.问题是您的正则表达式字符串变量有双
\\\\
而不是一个。
You can use您可以使用
rxp.replace("\\\\", "\\")
in .match
like this:在
.match
是这样的:
>>> print re.match(rxp.replace("\\\\", "\\"), _string)
<_sre.SRE_Match object at 0x10bf87c68>
>>> print re.match(rxp.replace("\\\\", "\\"), _string).groups()
('cat', 'dog')
EDIT:编辑:
You can also avoid getting double \\\\
like this: import re您还可以避免像这样获得双
\\\\
:import re
_pattern = "abba" #raw_input().strip()
_string = "catdogdogcat" #raw_input().strip()
hm = {}
rxp = ""
c = 1
for x in _pattern:
if x in hm:
rxp += hm[x]
continue
else:
rxp += "(.+)"
hm[x]="\\" + str(c)
c+=1
print rxp
print re.match(rxp,_string)
您应该使用字符串格式,而不是将rxp
硬编码到字符串中:
print re.match(r'%s'%rxp, _string)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.