Python重新"虚假逃脱错误"

rec*_*gle 10 python regex tkinter

我一直在搞乱python re modules .search方法.cur是来自Tkinter条目小部件的输入.每当我在条目小部件中输入"\"时,它都会抛出此错误.我不能确定错误是什么或如何处理它.任何见解都会非常感激.

cur是一个字符串

tup [0]也是一个字符串

片段:

se = re.search(cur, tup[0], flags=re.IGNORECASE)
Run Code Online (Sandbox Code Playgroud)

错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python26\Lib\Tkinter.py", line 1410, in __call__
    return self.func(*args)
  File "C:\Python26\Suite\quidgets7.py", line 2874, in quick_links_results
    self.quick_links_results_s()
  File "C:\Python26\Suite\quidgets7.py", line 2893, in quick_links_results_s
    se = re.search(cur, tup[0], flags=re.IGNORECASE)
  File "C:\Python26\Lib\re.py", line 142, in search
    return _compile(pattern, flags).search(string)
  File "C:\Python26\Lib\re.py", line 245, in _compile
    raise error, v # invalid expression
error: bogus escape (end of line)
Run Code Online (Sandbox Code Playgroud)

Bry*_*ley 15

"伪造逃生(行尾)"意味着你的模式以反斜杠结束.这与Tkinter无关.您可以在交互式shell中轻松复制错误:

>>> import re
>>> pattern="foobar\\"
>>> re.search(pattern, "foobar")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.py", line 142, in search
    return _compile(pattern, flags).search(string)
  File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.py", line 241, in _compile
    raise error, v # invalid expression
sre_constants.error: bogus escape (end of line)  
Run Code Online (Sandbox Code Playgroud)

解决方案?确保您的模式不会以单个反斜杠结束.

  • @ Anteater7171:反斜杠对正则表达式来说很特殊.您有两种选择:不要使用正则表达式或修改字符串,以便删除特殊含义.对于后者,添加额外的反斜杠就可以了(即:模式'\\'表示字面反斜杠). (2认同)

rtn*_*pro 12

此问题的解决方案是使用原始字符串作为替换文本.以下内容不起作用:

re.sub('this', 'This \\', 'this is a text')
Run Code Online (Sandbox Code Playgroud)

它会抛出错误:伪造逃生(行尾)

但以下工作会很好:

re.sub('this', r'This \\', 'this is a text')
Run Code Online (Sandbox Code Playgroud)

现在,问题是如何将程序运行时生成的字符串转换为Python中的原始字符串.你可以在这里找到解决方案.但我更喜欢使用更简单的方法来做到这一点:

def raw_string(s):
    if isinstance(s, str):
        s = s.encode('string-escape')
    elif isinstance(s, unicode):
        s = s.encode('unicode-escape')
    return s
Run Code Online (Sandbox Code Playgroud)

上述方法只能将ascii和unicode字符串转换为原始字符串.嗯,这对我来说很有用,直到约会:)