如何通过允许特定字符来使用Regex
验证EditText
。我的情况是:
密码规则:
(@,$,%,&,#,)
任何可接受的普通符号。我可以知道实现目标的正确方法是什么吗?--
发布于 2014-04-22 16:43:46
试试这个可能会有帮助
^(?=.*[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();
}
}
发布于 2018-06-01 21:35:41
对于Kotlin爱好者:
fun isValidPassword(password: String?) : Boolean {
password?.let {
val passwordPattern = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{4,}$"
val passwordMatcher = Regex(passwordPattern)
return passwordMatcher.find(password) != null
} ?: return false
}
发布于 2014-04-22 16:41:13
尝尝这个。
(/^(?=.*\d)(?=.*[A-Z])([@$%&#])[0-9a-zA-Z]{4,}$/)
(/^
(?=.*\d) //should contain at least one digit
(?=.*[@$%&#]) //should contain at least one special char
(?=.*[A-Z]) //should contain at least one upper case
[a-zA-Z0-9]{4,} //should contain at least 8 from the mentioned characters
$/)
https://stackoverflow.com/questions/23214434
复制相似问题