1

我正在做一个程序,用户可以使用正则表达式在文本中搜索,我想让匹配的文本被选中。所以我使用这段代码:

    public void onClick(View v) {
        try {
            switch (v.getId()) {
                case R.id.btn_search:
                    Matcher m = Pattern.compile(reg.getText().toString()).matcher(txt.getText());
                    int start = txt.getSelectionStart();
                    if (start != txt.getSelectionEnd()) {
                        start++;
                    }
                    if (start < 0 || start >= txt.length()) {
                        start = 0;
                    }
                    while (true) {
                        try {
                            m.find(start);
                            txt.setSelection(m.start(), m.end());
                            txt.requestFocus();
                            break;
                        } catch (IllegalStateException ex) {
                            if (start == 0) {
                                err_notfound.show();
                                break;
                            }
                            start = 0;
                        }
                    }
                    break;
            }
        } catch (PatternSyntaxException ex) {
            err_syntax.show();
        } catch (Throwable ex) {
            showException("onClick", ex);
        }
    }

但是代码没有按预期运行。当我手动将光标放在某个位置,然后按搜索按钮时,有时程序会将光标设置为 m.start() 但不会将选择扩展为 m.end()。我已经测试了程序,m.start() 和 m.end() 是不同的值。如果有人知道导致问题的原因,请告诉我。我会很感激的。

编辑:感谢您的帮助!我找到了这个问题的答案。它与用于移动光标和选择文本的图钉有关(我不知道它叫什么……)。如果它显示在文本字段中,并且调用了 setSelection(),则 EditText 将不会正确显示选择。但是,如果您随后使用 getSelectionStart() 和 getSelectionEnd(),您会发现它们与 m.getStart() 和 m.getEnd() 的值完全相同。这可能是一个错误。所以我的解决方案是先调用 clearFocus() 。修改后的代码是这样的:

                    txt.clearFocus();
                    while (true) {
                        try {
                            m.find(start);
                            txt.setSelection(m.start(), m.end());
                            txt.requestFocus();
                            break;
                        } catch (IllegalStateException ex) {
                            if (start == 0) {
                                err_notfound.show();
                                break;
                            }
                            start = 0;
                        }
                    }

它有效。

4

1 回答 1

1

I tested your code and put in one modiication.

 Matcher m = Pattern.compile("1*", Pattern.CASE_INSENSITIVE).matcher(txt.getText()); 

I then made sure that my EditText had only 1's and it highlighted the entire thing.

You many need to confirm that your Regular Expressions are written correctly. You could see more on regualr expressions here(same site I just used).

于 2012-09-26T13:16:08.220 回答