Android:正则表达式问题matcher.find()始终返回false

时间:2014-02-02 09:18:00

标签: java android regex

我想创建一个付款表格,如下例所示:

enter image description here

当用户填写信用卡号时,它应在编辑文本的左侧显示卡片徽标。以下是我开始使用的代码:

String pattern = "^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11})$";
final Pattern pattern1 = Pattern.compile(pattern);

edtCardNo.addTextChangedListener(new TextWatcher() {
        private boolean mFormatting; // this is a flag which prevents the
                                        // stack overflow.
        private int mAfter;

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub
            mAfter = after;
        }

        @Override
        public void afterTextChanged(Editable s) {
            Log.e("CCTest", "after text changed");
            // TODO Auto-generated method stub
            if (!mFormatting) {
                Log.e("CCTest", "after text changed if");
                mFormatting = true;
                // using US formatting...
                if (mAfter != 0) { // in case back space ain't clicked...
                    Log.e("CCTest",
                            "after text changed mAfter != 0 "
                                    + s.toString());
                    Matcher matcher = pattern1.matcher(s.toString());
                    Log.e("CCTest",
                            "after text changed mAfter != 0 "
                                    + matcher.find());
                    while (matcher.find()) {
                        Log.e("CCTest", "matcher find");
                        if (s.charAt(0) == '4') {
                            Log.e("CCTest", "matcher find if");
                            Toast.makeText(getApplicationContext(), "VISA",
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                }
                mFormatting = false;
            }
        }
    });
}

但是,matcher.find()总是返回false,因此toast消息没有显示出来。我没弄到错误的地方。

1 个答案:

答案 0 :(得分:2)

您的正则表达式可能存在问题。

尝试使用正则表达式定义here

这也是生成正则表达式的好网站