构建正则表达式以仅匹配 2 个单词 [英] Building regex to match 2 words only
本文介绍了构建正则表达式以仅匹配 2 个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使正则表达式仅匹配 2 个单词和一个步调.没有特殊符号,只有[a-zA-Z]
空格[a-zA-z]
.
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)
推荐答案
你想要 ^[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.
演示:
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
这篇关于构建正则表达式以仅匹配 2 个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文