我正在尝试编译一个正则表达式,以便能够从推文中累积一系列主题标签 (r'#\w+')。我希望能够编译两个正则表达式,它们可以从推文的开始和结束开始执行此操作。我正在使用 python 272,我的代码是这样的。
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
我不知道为什么我会得到这个,因为我在正则表达式模式中看不到不平衡的括号。
请您参考如下方法:
这一行在第一个 # 之后被注释掉了:
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
"""
