如何检查编辑文本视图是否包含2个空格?

时间:2015-06-17 19:39:04

标签: android android-fragments android-edittext android-view textview

目前,我的编辑文本视图会检查搜索的术语是否包含一个空格,如下所示:

if(mSearchView.getText().toString().contains(" ")

如何确保检查搜索视图中是否包含2个空格,例如:“here is is”

2 个答案:

答案 0 :(得分:1)

您可以使用正则表达式来执行此操作。使用这样的代码:

if(Pattern.matches("^\\w+\\s\\w+\\s\\w+$", mSearchView.getText().toString()))

另外,请务必检查mSearchView.getText()是否为空 - 您可能会收到NullReferenceException空白EditText内容。

最后,您可能想要创建一个类似这样的方法:

public static boolean containsTwoSpaces(Editable text) {
    if (text == null) return false;

    return Pattern.matches("^\\w+\\s\\w+\\s\\w+$", text.toString());
}

只是为了方便,清除并确保您不会碰到NullPointerException

答案 1 :(得分:0)

here

Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(s);
boolean found = matcher.find();
int mms=matcher.groupCount();
相关问题