Python:如何用正则表达式验证句子单词长度≥3且全小写
Got it, let's break down why your current regex isn't working and fix it properly.
The Problem with Your Current Regex
Your regex '([a-z\s]{3,})+$' is checking for blocks of 3+ lowercase letters or spaces repeated until the end of the string. That's why "hi world" returns True—because "hi " (h + i + space) is 3 characters, followed by "world" (5 characters), so the whole string fits the pattern. But this completely misses the requirement that each individual word needs to be at least 3 characters long.
The Correct Regex
We need to explicitly enforce that every word in the sentence has 3+ lowercase letters, with only spaces separating them. Here's the right pattern:
r'^[a-z]{3,}(?:\s[a-z]{3,})*$'
Let's break down what each part does:
^: Anchors the match to the start of the string (so we don't ignore leading invalid characters)[a-z]{3,}: Matches the first word—must be 3+ lowercase letters(?:\s[a-z]{3,})*: A non-capturing group that matches 0 or more instances of "space + 3+ lowercase letters" (this handles all subsequent words)$: Anchors the match to the end of the string (so we don't ignore trailing invalid characters)
Testing It Out
Let's verify with your examples and edge cases:
bool(re.compile(r'^[a-z]{3,}(?:\s[a-z]{3,})*$').match("hello world"))→ True (both words are ≥3 characters)bool(re.compile(r'^[a-z]{3,}(?:\s[a-z]{3,})*$').match("hi world"))→ False ("hi" is only 2 characters)bool(re.compile(r'^[a-z]{3,}(?:\s[a-z]{3,})*$').match("hello hi there"))→ False ("hi" fails the length check)bool(re.compile(r'^[a-z]{3,}(?:\s[a-z]{3,})*$').match("helloworld"))→ True (single valid word)
Optional: Allow Leading/Trailing Spaces
If you want to permit optional spaces at the start or end of the sentence, adjust the regex to include \s* at both ends:
r'^\s*[a-z]{3,}(?:\s[a-z]{3,})*\s*$'
This will match strings like " hello world " while still enforcing the word length rule.
Full Code Example
Here's a reusable function to implement this validation:
import re def is_valid_sentence(sentence): pattern = re.compile(r'^[a-z]{3,}(?:\s[a-z]{3,})*$') return bool(pattern.match(sentence)) # Test cases print(is_valid_sentence("hello world")) # Output: True print(is_valid_sentence("hi world")) # Output: False print(is_valid_sentence("test")) # Output: True print(is_valid_sentence("a b c")) # Output: False
内容的提问来源于stack exchange,提问作者Mila

