求匹配无首尾空格且含多连续空格字符串的Regex
Regex to Match Strings with Consecutive Spaces (No Leading/Trailing Spaces)
Perfect, I've got a regex that meets your exact needs, plus a breakdown of how it works and examples to test against.
The Regex
^(?!\s)(?=.*\s{2,})(?!.*\s$).+$
Breakdown of Each Part
Let's unpack what each segment does to ensure it hits all your rules:
^(?!\s): Negative lookahead at start — guarantees the string doesn't begin with any whitespace character.(?=.*\s{2,}): Positive lookahead — checks that somewhere in the string, there's at least one pair of consecutive spaces (\s{2,}matches 2+ spaces, so this covers 2, 3, or more in a row).(?!.*\s$): Negative lookahead at end — makes sure the string doesn't end with whitespace..+$: Matches one or more non-newline characters, so we don't match empty strings.
Valid Test Cases (Regex Returns True)
"hello world"(two consecutive spaces in the middle; no leading/trailing spaces)"foo bar baz"(three consecutive spaces between "foo" and "bar")"a b c d"(multiple sets of consecutive spaces throughout)"test123 456test"(consecutive spaces between numeric and alphabetic characters)
Invalid Test Cases (Regex Returns False)
" hello world"(starts with a space)"hello world "(ends with a space)"hello world"(only single spaces, no consecutive duplicates)" hello world "(leading and trailing spaces present)""(empty string)"singleword"(no spaces at all)
内容的提问来源于stack exchange,提问作者Saad
相关产品推荐
相关产品推荐

