Python re“假转义错误”

2024-05-20 16:25:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在使用python的re modules搜索方法。cur是Tkinter条目小部件的输入。每当我在entry小部件中输入“\”时,它就会抛出此错误。我不完全确定错误是什么或如何处理。任何洞察都将不胜感激。

cur是字符串

tup[0]也是一个字符串

代码段:

se = re.search(cur, tup[0], flags=re.IGNORECASE)

错误:

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)

Tags: inpyresearchtkinterlib错误line
3条回答

“伪转义(行尾)”表示模式以反斜杠结尾。这和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)  

解决办法?确保你的模式没有以一个反斜杠结束。

如果要在“tup[0]中搜索“cur”,则应通过“try:。。。除外:…”块捕获无效模式:

try :
    se = re.search(cur, tup[0], flags=re.IGNORECASE)
except re.error, e:
    # print to stdout or any status widget in your gui
    print "Your search pattern is not valid."
    # Some details for error:
    print e
    # Or some other code for default action.

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

re.sub('this', 'This \\', 'this is a text')

它将抛出错误:伪逃逸(行尾)

但是下面的方法很好:

re.sub('this', r'This \\', 'this is a text')

现在,问题是如何在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

上述方法只能将ascii和unicode字符串转换为原始字符串。好吧,到现在为止,这对我来说一直很有用:)

相关问题 更多 >