简体   繁体   English

android中用于不带空格的密码的正则表达式

[英]Regular Expression in android for password without spaces

I have a EditText field in android. 我在android中有一个EditText字段。 The password should contain minimum 4 characters and maximum 20 characters without spaces at the start or in the middle. 密码至少应包含4个字符,最多20个字符,开头或中间不能有空格。 Example blankspaceRaghu and RaghublankspaceRaghu should not be alllowed. 示例blankspaceRaghu和RaghublankspaceRaghu不应被允许。

Pass= password.getText().toString();    

Pattern p= Pattern.compile("[^\\S]+[a-z,A-Z]+");

Matcher m = p.matcher(Pass);
Pass= mEditTextPassword.getText().toString();
Pattern p = Pattern.compile("^[A-Za-z0-9]{4,20}$"); 
Matcher m = p.matcher(Pass);

Try this pattern: 试试这个模式:

"\\A\\w{4,20}\\z"

\\\\A stands for "beginning of the input". \\\\A代表“输入开始”。

\\\\w is any alphanumeric (az, AZ, 0-9) character. \\\\w是任何字母数字(az,AZ,0-9)字符。 When you don't allow digits, replace it with [a-zA-Z] 如果您不允许数字,请用[a-zA-Z]替换

{4,20} means the previous things between 4 and 20 times in a row. {4,20}表示连续4到20次之间的先前事物。

\\\\z is the end of the string. \\\\z是字符串的结尾。 You didn't mentioned if you allow spaces AFTER the password string. 您没有提到是否在密码字符串后留空格。 When you want to allow this, insert \\\\s* (nothing or any number of whitespaces) before \\\\z . 如果要允许此操作,请在\\\\z之前插入\\\\s* (不包含任何空格)。

More about regular expression syntax can be found in the documentation of java.util.regex.Pattern 有关正则表达式语法的更多信息,请参见java.util.regex.Pattern的文档。

I think you want to match with a RegEx of \\\\A\\\\S{4,20}\\\\Z . 我认为您想与\\\\A\\\\S{4,20}\\\\Z的RegEx匹配。 That's any non-whitespace characters, with a length between 4 and 20, matching the whole string. 那是任何非空格字符,长度在4到20之间,与整个字符串匹配。

Updated - Spaces are allowed at the end.... 已更新-结尾处允许有空格。

Pass= password.getText().toString();    
Pattern p= Pattern.compile("((?!\\s)\\A)(\\s|(?<!\\s)\\S){4,20}\\Z");
Matcher m = p.matcher(Pass);

This matches 这个匹配

  • Match start of string as long as it is not followed by a space 匹配字符串的开头,只要后面没有空格
  • Match 4 to 20 occurrences of either a space or a non space provided it is not prefixed by a space 匹配4到20次出现的空格或非空格,前提是该空格没有前缀
  • Match end of string 匹配字符串结尾

You could try negative matching - that way you don't have to fuss around with negated character classes. 您可以尝试否定匹配-这样,您就不必大惊小怪的字符类了。

Match the password against /\\s/ . 将密码与/\\s/匹配。 If it matches, you have spaces somewhere in it and it should be rejected. 如果匹配,则其中有空格,应将其拒绝。 If not, you're free to go. 如果没有,您可以自由走。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM