含多分组的正则表达式无法匹配括号问题求助
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:
- Group 1 (
^(\#)): Matches the leading#(ensures your string starts with this character, as required). - 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,456or1,234,567), which your original\d+[,]?\d+couldn't support. - 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. - 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 (like31,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
相关产品推荐
相关产品推荐

