Python re.compile. 不平衡括号错误

1 投票
4 回答
7535 浏览
提问于 2025-04-17 18:20

我正在尝试编写一个正则表达式,用来从推文中提取一系列的标签(r'#\w+')。我想要编写两个正则表达式,分别用于提取推文的开头和结尾的标签。我使用的是Python 2.7,下面是我的代码。

HASHTAG_SEQ_REGEX_PATTERN           = r"""
(                                       #Outermost grouping to match overall regex
#\w+                                    #The hashtag matching. It's a valid combination of \w+
([:\s,]*#\w+)*                          #This is an optional (0 or more) sequence of hashtags separated by [\s,:]*
)                                       #Closing parenthesis of outermost grouping to match overall regex
"""

LEFT_HASHTAG_REGEX_SEQ      = re.compile('^' + HASHTAG_SEQ_REGEX_PATTERN , re.VERBOSE | re.IGNORECASE)

当我执行编译正则表达式的那一行时,出现了以下错误:

sre_constants.error: unbalanced parenthesis

我不知道为什么会出现这个错误,因为在我的正则表达式中我看不出有什么不匹配的括号。

4 个回答

2

如果你按照下面的方式写这个模式,就不会遇到这个问题了:

HASHTAG_SEQ_REGEX_PATTERN = (
'('    #Outermost grouping to match overall regex
'#\w+'     #The hashtag matching. It's a valid combination of \w+
'([:\s,]*#\w+)*'    #This is an optional (0 or more) sequence of hashtags separated by [\s,:]*
')'    #Closing parenthesis of outermost grouping to match overall regex
)

我个人从来不使用 re.VERBOSE,因为我不想记住关于空格和其他规则的那些事情。

3

你有一些没有转义的井号(#),你想合法地使用它们,但VERBOSE让你感到困扰:

\#\w+
([:\s,]*\#\w+)*   #reported issue caused by this hash
5

这一行在第一个 # 后面被注释掉了:

        v----comment starts here
([:\s,]*#\w+)*  ...

把它转义:

([:\s,]*\#\w+)*  

这一行也是被注释掉了,但它不会导致括号不平衡哦 :)

v----escape me
#\w+                                    #The hashtag matching ... 

 

HASHTAG_SEQ_REGEX_PATTERN           = r"""
(                 # Outermost grouping to match overall regex
\#\w+             # The hashtag matching. It's a valid combination of \w+
([:\s,]*\#\w+)*   # This is an optional (0 or more) sequence of hashtags separated by [\s,:]*
)                 # Closing parenthesis of outermost grouping to match overall regex
"""

撰写回答