Python正则表达式引擎和模式中的括号

时间:2012-07-18 12:29:20

标签: python regex

我正在编写一个驱动程序来处理来自终端的特定类型的提示。

驱动程序中的代码正在查找从设备收到的特定模式,以了解何时发送其他命令或退出等。

驱动程序中的代码将模式作为正则表达式。我为正则表达式尝试了许多不同的模式组合来处理这个提示符'(Cisco Controller) >',但无济于事。我试图逃避括号'\(Cisco Controller\)\s*>',我尝试使用原始字符串 r'\(Cisco Controller\)\s*>',我尝试了多种其他组合,但我通常最终得到错误“不平衡括号”或“虚假转义字符”。为什么我不能让正则表达式引擎接受这种模式?

1 个答案:

答案 0 :(得分:1)

我发现您发布的字符串的原始版本没有任何问题...在字符串'(Cisco Controller) > Command to execute would be here'上进行测试时似乎匹配得很好。

Python 2.6.8 (unknown, Jun  9 2012, 11:30:32)
[GCC 4.5.3] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> regex = re.compile(r'\(Cisco Controller\)\s*>')
>>> match = regex.search('(Cisco Controller) > Command to execute would be here')
>>> match
<_sre.SRE_Match object at 0x7ff3e720>
>>>