我如何检查编辑文本视图是否包含 2 个空格?
how do i check if the edit text view contains 2 white spaces?
目前我的编辑文本视图检查搜索的词是否包含一个 space,如下所示:
if(mSearchView.getText().toString().contains(" ")
如何确保它检查搜索视图是否包含 3 个搜索词之间的 2 spaces 例如:"here it is"
参见here。
Pattern pattern = Pattern.compile("\s");
Matcher matcher = pattern.matcher(s);
boolean found = matcher.find();
int mms=matcher.groupCount();
您可以使用正则表达式来做到这一点。使用这样的代码:
if(Pattern.matches("^\w+\s\w+\s\w+$", mSearchView.getText().toString()))
还要确保检查 mSearchView.getText()
是否不为空 - 您可能会得到一个包含空白 EditText
内容的 NullReferenceException
。
最后你可能想创建一个这样的方法:
public static boolean containsTwoSpaces(Editable text) {
if (text == null) return false;
return Pattern.matches("^\w+\s\w+\s\w+$", text.toString());
}
只是为了方便、清理并确保您不会撞到 NullPointerException
。
目前我的编辑文本视图检查搜索的词是否包含一个 space,如下所示:
if(mSearchView.getText().toString().contains(" ")
如何确保它检查搜索视图是否包含 3 个搜索词之间的 2 spaces 例如:"here it is"
参见here。
Pattern pattern = Pattern.compile("\s");
Matcher matcher = pattern.matcher(s);
boolean found = matcher.find();
int mms=matcher.groupCount();
您可以使用正则表达式来做到这一点。使用这样的代码:
if(Pattern.matches("^\w+\s\w+\s\w+$", mSearchView.getText().toString()))
还要确保检查 mSearchView.getText()
是否不为空 - 您可能会得到一个包含空白 EditText
内容的 NullReferenceException
。
最后你可能想创建一个这样的方法:
public static boolean containsTwoSpaces(Editable text) {
if (text == null) return false;
return Pattern.matches("^\w+\s\w+\s\w+$", text.toString());
}
只是为了方便、清理并确保您不会撞到 NullPointerException
。