如何只匹配两个单词?

时间:2013-10-23 14:09:05

标签: java regex

如何只匹配由一个或多个空格分隔的两个单词?

[\w]+[\s]+[\w]+

匹配:

one two
one two three //but this should not match as it countains more than 2 words

1 个答案:

答案 0 :(得分:5)

您可以将此正则表达式用于行开始和结束锚点:

^\\s*\\w+\\s+\\w+\\s*$

请注意^$的使用,确保只有空格分隔的two word string匹配。

RegEx参考:http://regular-expressions.info

相关问题