1

我正在尝试使正则表达式仅匹配 2 个单词和一个单步。没有特殊符号,只有[a-zA-Z]空格[a-zA-z]

Foo Bar      # Match    (two words and one space only)
Foo          # Mismatch (only one word)
Foo  Bar     # Mismatch (2 spaces)
Foo Bar Baz  # Mismatch (3 words)
4

1 回答 1

7

你要^[a-zA-Z]+\s[a-zA-Z]+$

^   # Matches the start of the string
+   # quantifier mean one or more of the previous character class 
\s  # matches whitespace characters
$   # Matches the end of the string

锚点^$在这里很重要。

演示

if "foo bar" =~ /^[a-zA-Z]+\s[a-zA-Z]+$/ 
    print "match 1"
end 
if "foo  bar" =~ /^[a-zA-Z]+\s[a-zA-Z]+$/ 
    print "match 2"
end 
if "foo bar biz" =~ /^[a-zA-Z]+\s[a-zA-Z]+$/ 
    print "match 3"
end 

输出:

Match 1
于 2013-01-04T09:22:05.007 回答