Building regex to match 2 words only

为君一笑 提交于 2021-02-04 21:29:27

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!