问题
I'm trying to make regexp that match only 2 words and a single pace between. No special symbols, only [a-zA-Z]
space [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)
回答1:
You want ^[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
The anchors ^
and $
are important here.
Demo:
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
Output:
Match 1
来源:https://stackoverflow.com/questions/14154263/building-regex-to-match-2-words-only