正则表达式需求:根据字符串特征匹配返回对应响应值
Solution for Regex-Based Response Matching
Let's fix your regex approach by first clarifying the exact rules for each scenario and then implementing a clean, priority-based check (since some scenarios overlap if we don't order them correctly):
Step 1: Clarify Scenario Rules
Let's restate your requirements with precise conditions to avoid ambiguity:
- Scenario 4 (return 'a'): The string contains only whitespace characters (spaces, tabs, newlines, etc.)
- Scenario 2 (return 'y'): String ends with
?and has no lowercase letters (all letters are uppercase; non-letter characters like spaces/digits are allowed) - Scenario 1 (return 'x'): String ends with
?but has at least one lowercase letter - Scenario 3 (return 'z'): Either the string ends with
!, OR it's all uppercase (no lowercase letters) and does NOT end with?
Step 2: Implement the Logic
We'll use a combination of direct string checks and regex to make the code readable and efficient. Here's the full implementation:
import re def get_response(phrase): # Check Scenario 4 first: only whitespace characters if re.fullmatch(r'\s+', phrase): return 'a' # Check for ?-ending scenarios (Scenarios 1 and 2) if phrase.endswith('?'): # Scenario 2: No lowercase letters in the entire string if re.fullmatch(r'[^a-z]*\?', phrase): return 'y' # Scenario 1: Has at least one lowercase letter else: return 'x' # Check Scenario 3: Ends with ! OR all uppercase (no ? at end) if phrase.endswith('!') or re.fullmatch(r'[^a-z]*', phrase): return 'z' # Fallback for edge cases not covered by your 4 scenarios return None
Step 3: Test with Your Examples
Let's verify this works with your sample phrases:
phrase1 = "Simple String with some UPPercase in Between ends with?"→ Returnsx(ends with ?, has lowercase letters)phrase2 = "BIG STRING ALL CAPS ENDS WITH?"→ Returnsy(ends with ?, no lowercase letters)phrase3_a = "ALLCAPSSTRING NOTHING AT THE END OF STRING"→ Returnsz(all uppercase, no ? at end)phrase3_b = "Any String with ALL UPPERCASE (or not) but ends with!"→ Returnsz(ends with !)phrase4 = "\t\t\t\t"→ Returnsa(only whitespace)
Why Your Original Regex Failed
- Removing all whitespace with
re.sub(r'[\s]','',phrase)was unnecessary—spaces don't affect whether a string is "all uppercase" - Your regex patterns only checked the last character or single characters, not the entire string's structure
- The pattern for Scenario 3 didn't capture the two distinct conditions (ends with !, or all uppercase without a ?)
内容的提问来源于stack exchange,提问作者pyeR_biz
相关产品推荐
相关产品推荐

