Android中密码字段的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23214434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regular Expression In Android for Password Field
提问by IntelliJ Amiya
How can i validating the EditText
with Regex
by allowing particular characters .
My condition is :
我如何通过允许特定字符来验证EditText
with Regex
。我的条件是:
Password Rule:
密码规则:
- One capital letter
- One number
One symbol
(@,$,%,&,#,)
whatever normal symbols that are acceptable.May I know what is the correct way to achieve my objective?
- 一个大写字母
- 一号
一个符号,
(@,$,%,&,#,)
任何可接受的正常符号。我可以知道实现目标的正确方法是什么吗?
回答by Biraj Zalavadia
Try this may helps
试试这可能有帮助
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\S+$).{4,}$
How it works?
这个怎么运作?
^ # 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
How to Implement?
如何实施?
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();
}
}
回答by Lavekush Agrawal
Try this.
尝试这个。
(/^(?=.*\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
$/)
回答by KingSeg
And for the Kotlinlovers :
对于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
}
回答by CONvid19
try {
if (subjectString.matches("^(?=.*[@$%&#_()=+???<>£§{}\[\]-])(?=.*[A-Z])(?=.*[a-z])(?=.*\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
(?=.*[A-Z]) -> Must have at least 1 upper case letter
(?=.*[a-z]) -> Must have at least 1 lower case letter
(?=.*\d) -> Must have at least 1 digit
(?<=.{4,})$") -> Must be equal or superior to 4 chars.
回答by Hiren Patel
I'm too late to answer but still it may help you.
我来不及回答,但它仍然可以帮助你。
I've worked with Kotlin
.
我曾与Kotlin
.
Add following function.
添加以下功能。
private fun isValidPassword(password: String): Boolean {
val pattern: Pattern
val matcher: Matcher
val specialCharacters = "-@%\[\}+'!/#$^?:;,\(\"\)~`.*=&\{>\]<_"
val PASSWORD_REGEX = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[$specialCharacters])(?=\S+$).{8,20}$"
pattern = Pattern.compile(PASSWORD_REGEX)
matcher = pattern.matcher(password)
return matcher.matches()
}
Function description:
功能说明:
- (?=.*[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 replace with your special characters
- (?=\S+$) # no whitespace allowed in the entire string .{8,} # anything, at least six places though
- (?=.*[0-9]) # 一个数字必须至少出现一次
- (?=.*[az]) # 小写字母必须至少出现一次
- (?=.*[AZ]) # 大写字母必须至少出现一次
- (?=. [-@%[}+'!/#$^?:;,(")~`.=&{>]<_]) # 一个特殊字符必须至少出现一次 用你的特殊字符替换
- (?=\S+$) # 整个字符串中不允许有空格 .{8,} # 任何东西,至少有六个地方
You can modify it as needed.
您可以根据需要对其进行修改。
Hope it helps.
希望能帮助到你。
回答by Benjamin Basmaci
As an addition to the answers already given, I would suggest a different route for identifying special characters and also would split up the check for the different rules.
作为对已经给出的答案的补充,我会建议使用不同的方法来识别特殊字符,并且还会针对不同的规则拆分检查。
First splitting it up: Instead of making one big rule, split it and check every rule separately, so that you are able to provide feedback to the user as to what exactly is wrong with his password. This might take a bit longer but in something like a password checkup this will not be noticable. Also, this way the conditions are more readable.
首先拆分:不是制定一个大规则,而是拆分它并单独检查每个规则,以便您能够向用户提供有关其密码究竟有什么问题的反馈。这可能需要更长的时间,但在诸如密码检查之类的事情中,这不会引起注意。此外,这种方式的条件更具可读性。
Secondly, instead of checking for a list of special characters, you could flip it and check if the password contains any characters that are neither letters of the latin alphabet (a-zA-Z) nor digits (0-9). That way you don't "forget" special characters. For example, lets say you check specifically but in your check you forget a character like "{”. With this approach, this can't happen. You can extend that list by things you don't consider to be special characters explicitly, for example a space. In kotlin
, it would look like this:
其次,您可以翻转它并检查密码是否包含既不是拉丁字母表 (a-zA-Z) 也不是数字 (0-9) 的任何字符,而不是检查特殊字符列表。这样你就不会“忘记”特殊字符。例如,假设您专门检查,但在检查中忘记了像“{”这样的字符。使用这种方法,这不会发生。您可以通过不明确认为是特殊字符的内容来扩展该列表,例如例如一个空格。在 中kotlin
,它看起来像这样:
val errorText = when {
/* Rule 1 */
!password.contains(Regex("[A-Z]")) -> "Password must contain one capital letter"
/* Rule 2 */
!password.contains(Regex("[0-9]")) -> "Password must contain one digit"
/* Rule 3, not counting space as special character */
!password.contains(Regex("[^a-zA-Z0-9 ]")) -> "Password must contain one special character"
else -> null
}
Depending on your encoding, you can also use regex and define your special characters using ranges of hex codes like
根据您的编码,您还可以使用正则表达式并使用十六进制代码范围定义您的特殊字符,例如
Reges("[\x00-\x7F]")
回答by ahmed_khan_89
you can use the class Patern
than Matcher
for every checking format.
您可以使用该类而Patern
不是Matcher
每种检查格式。
I give you an exemple of use :
我给你一个使用的例子:
Pattern pattern = Pattern.compile(".+@.+\.[a-z]+");
Matcher matcher = pattern.matcher(myEmailString);
if (!myEmailString.contains("@") || !matcher.matches()) {
// error in the email : do staff
myEmailView.setError("invalid email !");
}
回答by Moaz Rashad
Most common password validation is
最常见的密码验证是
- At least 8 character
- Require numbers
- Require special character
- Require uppercase letters
- Require lowercase letters
- 至少 8 个字符
- 需要数字
- 需要特殊字符
- 需要大写字母
- 需要小写字母
Regex:
正则表达式:
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[\\/%§"&“|`′}{°><:.;#')(@_$"!?*=^-]).{8,}$
Kotlin code:
科特林代码:
val PASSWORD_REGEX_PATTERN = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[\\/%§"&“|`′}{°><:.;#')(@_$"!?*=^-]).{8,}$"
fun isValidPassword(password: String?): Boolean {
val pattern: Pattern =
Pattern.compile(PASSWORD_REGEX_PATTERN)
val matcher: Matcher = pattern.matcher(password)
return matcher.matches()
}
online regex validator to check it:
在线正则表达式验证器来检查它:
回答by Ana Laura Anguiano Cruz
None of the above worked for me.
以上都不适合我。
What worked for me:
什么对我有用:
fun isValidPasswordFormat(password: String): Boolean {
val passwordREGEX = Pattern.compile("^" +
"(?=.*[0-9])" + //at least 1 digit
"(?=.*[a-z])" + //at least 1 lower case letter
"(?=.*[A-Z])" + //at least 1 upper case letter
"(?=.*[a-zA-Z])" + //any letter
"(?=.*[@#$%^&+=])" + //at least 1 special character
"(?=\S+$)" + //no white spaces
".{8,}" + //at least 8 characters
"$");
return passwordREGEX.matcher(password).matches()
}
Source: Coding in Flow
资料来源:流中编码
Hope it helps someone.
希望它可以帮助某人。