变量中的 Python 正则表达式

标签 python regex exception

代码迭代 #2

使用 stringVar = r'string' 将 var1 更改为原始字符串效果很好。使用下面的代码我现在得到一个异常(exception):

Traceback (most recent call last):
  File "regex_test.py", line 8, in <module>
    pattern = re.compile(var2 + "(.*)")
  File "/usr/lib/python2.7/re.py", line 190, in compile
    return _compile(pattern, flags)
  File "/usr/lib/python2.7/re.py", line 242, in _compile
    raise error, v # invalid expression
sre_constants.error: unbalanced parenthesis

--

#!/usr/bin/python

import re

var1 = r'\\some\String\to\Match'
var2 = '\\\\some\\String\\'

pattern = re.compile(var2 + "(.*)")
found = pattern.match(var1, re.IGNORECASE)

if found:
    print "YES"
else:
    print "NO"

我想在我的正则表达式中包含一个变量。这个问题与this other question有关,但通过使用编译模式与匹配中的变量略有不同。根据我所阅读的所有内容,下面的示例代码应该可以工作。

#!/usr/bin/python

import re

var1 = re.escape('\\some\String\to\Match') # A windows network share
var2 = "\\\\some\\String\\"

print var1 # Prints \\some\\String\ o\\Match
print var2 # Prints \\some\String\

pattern = re.compile(var2)
found = pattern.match(var1 + "(.*)", re.IGNORECASE)

if found:
    print "YES"
else:
    print "NO"

当我打印出我的变量时,我看到了一些奇怪的行为。我认为 re.escape 会转义字符串中所有需要的字符。

当我在 Ubuntu 12.4.1 上执行 Python 2.7 中的代码时,出现以下异常

Traceback (most recent call last):
  File "regex_test.py", line 11, in <module>
    pattern = re.compile(var2)
  File "/usr/lib/python2.7/re.py", line 190, in compile
    return _compile(pattern, flags)
  File "/usr/lib/python2.7/re.py", line 242, in _compile
    raise error, v # invalid expression
sre_constants.error: bogus escape (end of line)

我错过了什么导致抛出异常?

最佳答案

Python 的 \t 是一个单个 字符。您可能想要使用 r''(您可以通过谷歌搜索“原始字符串”来了解更多信息)来避免该问题。

\ 字符也是如此。

为了证明这一点,请尝试在 re.escape 中打印字符串,然后再输入它。它应该是有道理的。

这就是您要找的:

var1 = re.escape(r'\\some\String\to\Match')

关于变量中的 Python 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13019225/

相关文章:

Python:根据用户想要的文件导入文件

python - 在 appengine 中测试 error_handlers

java - IntelliJ 说 "\\"(匹配单个反斜杠)是 Pattern.compile 的非法/不受支持的转义序列

python - 如何从 KeyError 中获取关键信息

c++ - 在 C++ 中捕获错误的数组引用

python - 在numpy数组中查找大量满足条件的连续值

python - 使用 CSV 数据对对象进行排序

regex - "lineinfile": add new line (with PATH=) or append to existing line (with PATH=)

javascript - 正则表达式中的 "?-mix:"是什么意思

java - 防止 Java 在某些异常情况下打印堆栈跟踪