Android中的密码字段的正则expression式

我如何通过允许特定的字符validationEditText Regex 。 我的情况是:

密码规则:

  1. 一个大写字母
  2. 一个号码
  3. 一个符号 (@,$,%,&,#,)任何可接受的普通符号。

    请问我有什么方法可以实现我的目标?

Solutions Collecting From Web of "Android中的密码字段的正则expression式"

试试这可能有所帮助

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

怎么运行的?

 ^ # start-of-string (?=.*[0-9]) # a digit must occur at least once (?=.*[az]) # a lower case letter must occur at least once (?=.*[AZ]) # 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])(?=.*[az])(?=.*[AZ])(?=.*[@#$%^&+=])(?=\\S+$).{4,}$"; pattern = Pattern.compile(PASSWORD_PATTERN); matcher = pattern.matcher(password); return matcher.matches(); } } 

尝试这个。

 (/^(?=.*\d)(?=.*[AZ])([@$%&#])[0-9a-zA-Z]{4,}$/) (/^ (?=.*\d) //should contain at least one digit (?=.*[@$%&#]) //should contain at least one special char (?=.*[AZ]) //should contain at least one upper case [a-zA-Z0-9]{4,} //should contain at least 8 from the mentioned characters $/) 
 try { if (subjectString.matches("^(?=.*[@$%&#_()=+?»«<>£§€{}\\[\\]-])(?=.*[AZ])(?=.*[az])(?=.*\\d).*(?<=.{4,})$")) { // String matched entirely } else { // Match attempt failed } } catch (PatternSyntaxException ex) { // Syntax error in the regular expression } (?=.*[@\$%&#_()=+?»«<>£§€{}.[\]-]) -> must have at least 1 special character (?=.*[AZ]) -> Must have at least 1 upper case letter (?=.*[az]) -> Must have at least 1 lower case letter (?=.*\\d) -> Must have at least 1 digit (?<=.{4,})$") -> Must be equal or superior to 4 chars. 

每个检查格式都可以使用PaternMatcher类。

我给你一个使用的例子:

  Pattern pattern = Pattern.compile(".+@.+\\.[az]+"); Matcher matcher = pattern.matcher(myEmailString); if (!myEmailString.contains("@") || !matcher.matches()) { // error in the email : do staff myEmailView.setError("invalid email !"); }