【问题标题】:how do i check if the edit text view contains 2 white spaces?如何检查编辑文本视图是否包含 2 个空格?
【发布时间】:2015-09-03 05:41:15
【问题描述】:

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

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

如何确保它检查搜索视图是否在 3 个搜索词之间包含 2 个空格,例如:“这里是”

【问题讨论】:

  • 为你的 mSearchView 添加一个文本改变监听器然后 onTextChange 你可以检查空格。
  • 在这种情况下这是不必要的工作,可能会导致应用程序性能下降。除非真的需要实时完成,否则我不建议这样做。

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


【解决方案1】:

here

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

【讨论】:

  • 我不想限制我的单词,只想识别单词之间的2个或更多空格
【解决方案2】:

您可以使用正则表达式来做到这一点。使用这样的代码:

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

【讨论】:

  • 它在 "^\w\s\w\s\w$" 上显示一个错误 无效的转义序列(有效的是 \b \t \n \f \r \" \' \ \ )
  • 我的错 - 犯了一个错误。更新了答案
  • 忘记转义反斜杠了...呃...再次更新了答案并在 NetBeans 中进行了测试。
  • 感谢您的详细回答,但目前我正在执行以下操作: if((searchTerm.contains(mSearchView.getText().toString().toLowerCase(Locale.ENGLISH) + " " + mSearchView .getText().toString().toLowerCase(Locale.ENGLISH))。你建议我如何将上面的代码合并到我的代码中
猜你喜欢
  • 1970-01-01
  • 2021-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-09
相关资源
最近更新 更多