0

我有一个onTextChangedListener监视 EditText 以查看它是否包含任何像这样的“非单词”字符;

input.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {}
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (input.getText().toString().contains("\\W")) {
                input.setError("Error");
            }
            else{

            }

        }});

但是,我的代码似乎无法识别("\\W")为非单词字符。我用它来检查其他 EditTexts,但在这些情况下,它只是替换任何非单词字符而不提示哪个工作正常;

String locvalidated = textLocation.getText().toString().replaceAll("\\W", "-");

看来我不能\\W用来检查 EditText 是否包含这样的字符,只能替换它们。有解决方法吗?

4

1 回答 1

0

String.contains()不检查正则表达式。所以在你的情况下,你只是在检查String "\W". 它做了一个简单的(子)字符串比较。

一种解决方法是

String s = input.getText().toString();
boolean hasNonWord = !s.equals(s.replaceAll("\\W", "x"));

所以,在你的情况下:

public void onTextChanged(CharSequence s, int start, int before, int count) {
    String s = input.getText().toString();
    if (!s.equals(s.replaceAll("\\W", "x"))) {
        input.setError("Error");
    } else {
        input.setError(null);
    }
}
于 2013-10-06T22:42:05.737 回答