how do i check if the edit text view contains 2 white spaces?

808 Views Asked by At

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"

2

There are 2 best solutions below

4
On BEST ANSWER

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.

1
On

See here.

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