You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python正则表达式报错sre_constants.error:缺少闭合括号,求协助

Fixing sre_constants.error: missing ), unterminated subpattern in Your Regex Code

Hey Gaurav, sorry to hear you're stuck on this regex error while working through Dive into Python 3—let's break down what's going on and fix it.

What's Causing the Error?

This error message is telling you clearly: your regular expression has an unterminated subpattern. That means you've opened a grouping with a left parenthesis ( somewhere in your regex, but never closed it with a matching right parenthesis ).

Common Scenarios & Fixes

Let's walk through the most likely issues and how to resolve them:

  1. Missing closing parenthesis for a capture group
    If you wrote a regex that creates a capture group but forgot the closing ), like this:

    import re
    # Wrong: only one (, no matching )
    pattern = re.compile(r'(\w+-\d+')
    match = pattern.search('user-123')
    

    Fix it by adding the missing closing parenthesis:

    # Correct: group is properly closed
    pattern = re.compile(r'(\w+-\d+)')
    
  2. Unescaped literal parentheses
    If you're trying to match a literal ( character in your input (not create a regex group), you need to escape it with \(. Forgetting to escape the corresponding ) will also trigger this error. Example:

    # Wrong: trying to match (123) but didn't escape the closing )
    pattern = re.compile(r'\(123')
    

    Fix it by escaping both literal parentheses:

    # Correct: matches the literal string (123)
    pattern = re.compile(r'\(123\)')
    
  3. Nested groups with mismatched parentheses
    When using nested groups, make sure every opening ( has a corresponding closing ) in the right order. For example:

    # Wrong: nested group missing a closing )
    pattern = re.compile(r'((\w+)-\d+')
    

    Fix by adding the missing closing parenthesis:

    # Correct: all groups are properly closed
    pattern = re.compile(r'((\w+)-\d+)')
    

Quick Debugging Tip

A fast way to spot the issue is to count the number of ( and ) in your regex string. They should be exactly equal. If they're not, you know exactly where to focus your troubleshooting!

If you share your exact code snippet, we can pinpoint the exact line, but based on the error message, this parenthesis mismatch is definitely the root cause.

内容的提问来源于stack exchange,提问作者Gaurav Kochar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:02:03