重新不​​工作,奇怪的人物

时间:2011-03-13 07:49:08

标签: python regex string

textfields="""Conjugation of suorittaa """ 
stry2= """Conjugation"""
stryc=re.compile(stry2, re.DOTALL)
print 'textfields=', textfields, '  stry2=', stry2
LtryM=re.search(stryc, textfields); print 'LtryM', LtryM 

我找不到re字“”“Conjugation”“”in string“”“suorittaa的共轭”“”。 我最后我印了字ans字符串。 出现了,而不是“”“共轭”“”我得到印刷字“”“xxxConjugation”“”,其中xxx是奇怪的字符。

我如何解决这个问题。我还尝试将两个字符串编码为'utf-8'。结果是一样的。 这些奇怪的字符只出现在单词的前面,在conjug.py中不可见。

3 个答案:

答案 0 :(得分:1)

根据您提供的信息,您的问题无法重现:

>>> import re
>>> textfields="""Conjugation of suorittaa """
>>> stry2= """Conjugation"""
>>> stryc=re.compile(stry2, re.DOTALL)
>>> print 'textfields=', textfields, '  stry2=', stry2
textfields= Conjugation of suorittaa    stry2= Conjugation
>>> LtryM=re.search(stryc, textfields); print 'LtryM', LtryM
LtryM <_sre.SRE_Match object at 0x0195A870>
>>> LtryM.group(0)
'Conjugation'
>>> print repr(textfields)
'Conjugation of suorittaa '
>>> print repr(stry2)
'Conjugation'
>>>

尝试以上述方式自行复制,可以复制/粘贴到SO中,并准确显示我的所作所为和结果。

[Python 2.7.1; Windows 7 32位]

答案 1 :(得分:0)

如果您有捕获组,则AFAIK,searchmatch会返回匹配对象。要获得您期望的行为,请使用findall

In [23]: textfields="""Conjugation of suorittaa """ 

In [24]: stry2= """Conjugation"""

In [25]: ls = re.findall(stry2 , textfields )

In [26]: ls
Out[26]: ['Conjugation']

如果这不是您的查询,请详细说明您的具体操作。

答案 2 :(得分:0)

发布的代码应该找到匹配的罚款。请注意,re.search会返回MatchObject,您不应该直接打印出来 - 您可能希望打印出匹配的文字:

print LtryM.group(0)

这应该打印'Conjugation'。