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

含多分组的正则表达式无法匹配括号问题求助

Let's fix that regex for you! Your original pattern has a couple of issues that are causing it to misbehave with parentheses and flexible number formatting—here's a solution tailored to your exact requirements:

The Corrected Regex

^(\#)(\d+(?:,\d+)*)([^(]+)\(.*\)$

Breakdown of Each Group

Let's walk through how this addresses all your needs:

  1. Group 1 (^(\#)): Matches the leading # (ensures your string starts with this character, as required).
  2. Group 2 ((\d+(?:,\d+)*)): Captures numbers with optional comma separators. The (?:,\d+)* non-capturing group lets it handle any valid comma-formatted number (e.g., 31,456 or 1,234,567), which your original \d+[,]?\d+ couldn't support.
  3. Group 3 (([^(]+)): Grabs all text between the number and the first opening parenthesis. Unlike your original greedy .*, this uses a negated character set to stop exactly at the first (, avoiding over-matching.
  4. Final Segment (\(.*\)$): Matches the entire parenthetical section (from ( to )) so you can ignore or remove it easily.

Example Usage (Python)

Here's how you'd extract the values and clean the string:

import re

input_text = "#31,456 in this category (Top 100 of category)"
pattern = r"^(\#)(\d+(?:,\d+)*)([^(]+)\(.*\)$"
match_result = re.match(pattern, input_text)

if match_result:
    # Extract your target values
    extracted_number = match_result.group(2)
    category_text = match_result.group(3).strip()  # Trim extra whitespace if needed
    
    # Generate cleaned output (remove parentheses, keep leading # if desired)
    cleaned_string = match_result.group(1) + extracted_number + category_text
    
    print(f"Extracted number: {extracted_number}")  # Output: 31,456
    print(f"Text between number and parenthesis: {category_text}")  # Output: in this category
    print(f"Cleaned string: {cleaned_string}")  # Output: #31,456 in this category

Why Your Original Regex Failed

  • The greedy .* in your pattern would match all characters up to the last opening parenthesis (if there were multiple), instead of stopping at the first one.
  • Your number matching (\d+[,]?\d+) only works for numbers with exactly one comma (like 31,456) and fails for longer formatted numbers.
  • The [\(+] group was unnecessary and incorrectly formatted—it didn't account for the closing parenthesis, so you couldn't fully target the parenthetical section.

内容的提问来源于stack exchange,提问作者Mher Harutyunyan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:27:30