本文介绍了Android中用于密码字段的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何通过允许特定字符来用Regex验证EditText.我的状况是:

How can i validating the EditText with Regex by allowing particular characters .My condition is :

密码规则:

  1. 一个大写字母

一个号码

一个符号 (@,$,%,&,#,)任何可接受的常规符号.

One symbol (@,$,%,&,#,) whatever normal symbols that are acceptable.

我可以知道实现我的目标的正确方法是什么吗?

May I know what is the correct way to achieve my objective?

推荐答案

尝试一下可能会帮助

^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{4,}$

它如何工作?

^                 # start-of-string
(?=.*[0-9])       # a digit must occur at least once
(?=.*[a-z])       # a lower case letter must occur at least once
(?=.*[A-Z])       # an upper case letter must occur at least once
(?=.*[@#$%^&+=])  # a special character must occur at least once you can replace with your special characters
(?=\\S+$)          # no whitespace allowed in the entire string
.{4,}             # anything, at least six places though
$                 # end-of-string

如何实施?

public class MainActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText editText = (EditText) findViewById(R.id.edtText);
        Button btnCheck = (Button) findViewById(R.id.btnCheck);

        btnCheck.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (isValidPassword(editText.getText().toString().trim())) {
                    Toast.makeText(MainActivity.this, "Valid", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "InValid", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    public boolean isValidPassword(final String password) {

        Pattern pattern;
        Matcher matcher;

        final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{4,}$";

        pattern = Pattern.compile(PASSWORD_PATTERN);
        matcher = pattern.matcher(password);

        return matcher.matches();

    }

}

这篇关于Android中用于密码字段的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 21:25