0

Currently my edit text view checks if the searched term contains one space as follows:

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

How do I make it such that it makes sure it checks if the searchview contains 2 spaces between 3 search terms for example: "here it is"

  • Add a text change listener to your mSearchView then onTextChange you can check for spaces. – ArbenMaloku Jun 17 '15 at 20:09
  • That is an unnecessary effort in this case and may lead to decrearing applications performance. Unless it is really needed to be done in realtime, I would not recommend going that way. – rasmeta Jun 17 '15 at 20:46

2 Answers2

0

See here.

Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(s);
boolean found = matcher.find();
int mms=matcher.groupCount();
Community
  • 1
  • 1
Syed Ali Naqi
  • 701
  • 7
  • 15
  • I don't want to limit my words, just want to recognize 2 or more spaces between words –  Jun 17 '15 at 19:59
0

You can use a regular expression to do that. Use code like this one:

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

Also make sure to check if mSearchView.getText() is not null - you probably will get a NullReferenceException with a blank EditText content.

In the end you may want to create a method like this one:

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

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

just for convenience, clearance and making sure you don't bump into a NullPointerException.

rasmeta
  • 465
  • 2
  • 12
  • it shows me an error on "^\w\s\w\s\w$" Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ \ ) –  Jun 17 '15 at 19:58
  • My bad - made a mistake. Updated the Answer – rasmeta Jun 17 '15 at 20:06
  • Forgot about escaping backslashes... Duh... Updated the answer once more and tested it out in NetBeans. – rasmeta Jun 17 '15 at 20:43
  • Thanks for the detailed answer, but currently I am doing as follows: if((searchTerm.contains(mSearchView.getText().toString().toLowerCase(Locale.ENGLISH) + " " + mSearchView.getText().toString().toLowerCase(Locale.ENGLISH)). How do you suggest I should incorporate the above code into my code –  Jun 18 '15 at 00:55