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

Python:如何用正则表达式验证句子单词长度≥3且全小写

Fixing Your Regex for Validating Word Lengths in Sentences

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:47:48