如何在Python3中不使用Regex移除未闭合括号及对应内容?
Hey there! Let's work through this problem since regex isn't on the table. The core idea here is to use a stack to track opening parentheses—this is a tried-and-true method for handling bracket matching scenarios.
Step-by-Step Explanation
Your goal is to remove unclosed parentheses and their contained content, which in your example means turning esdfd((esdf)(esdf into esdfd((esdf). Here's how to do it:
Track Matching Parentheses:
- We'll iterate through the string, using a stack to keep track of the indices of opening parentheses
(. - When we hit a closing parenthesis
), if the stack isn't empty, we pop the last opening parenthesis index (this means we found a matching pair). We'll also record the position of the last successfully matched closing parenthesis—this is key because anything after this point that's part of an unclosed bracket needs to be removed.
- We'll iterate through the string, using a stack to keep track of the indices of opening parentheses
Truncate the String:
- If there are no matching bracket pairs at all, we just take everything up to the first unclosed opening parenthesis.
- If there are valid pairs, we truncate the string at the last matching closing parenthesis. This keeps all valid content (including any unclosed opening parentheses that wrap valid pairs, like the outer
(in your example) and removes the unclosed trailing segment.
Example Code (Python)
Here's a concrete implementation that follows this logic:
def remove_unclosed_parentheses(input_str): stack = [] last_matched_right = -1 # Track matching pairs (optional, but helps clarify) matched_pairs = {} for idx, char in enumerate(input_str): if char == '(': stack.append(idx) elif char == ')': if stack: left_idx = stack.pop() matched_pairs[left_idx] = idx matched_pairs[idx] = left_idx # Update the last matched closing parenthesis position if idx > last_matched_right: last_matched_right = idx if last_matched_right == -1: # No valid pairs found; remove everything from first '(' onwards first_open = next((i for i, c in enumerate(input_str) if c == '('), len(input_str)) return input_str[:first_open] else: # Keep all content up to and including the last valid closing parenthesis return input_str[:last_matched_right + 1] # Test with your input test_str = "esdfd((esdf)(esdf" print(remove_unclosed_parentheses(test_str)) # Output: esdfd((esdf)
This code works exactly as you need it to for your example, and it handles edge cases too—like strings with no valid pairs, or multiple layers of nested brackets.
内容的提问来源于stack exchange,提问作者user11045254
相关产品推荐
相关产品推荐

