安卓 java正则表达式查找字符串中的所有空格
我看到了许多建议,让正则表达式在字符串中查找空格,但到目前为止,这些建议都没有奏效。是的,使用for next循环在字符串中循环的概念将起作用。我真的很想学习如何使用正则表达式和模式匹配器来实现这一点!我的问题是,我需要向我的正则表达式字符串添加什么以及在哪里添加,以便它返回FALSE?下面的代码我添加了许多(\\s)的化身,但都没有用。我不想删除空格
我测试了建议作为副本的代码,但它不起作用,请参见注释中建议的链接
String tstr = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]";
String astr = etPW.getText().toString().trim();
Pattern regex = Pattern.compile(tstr);
Matcher regexMatcher = regex.matcher(astr);
boolean foundMatch = regexMatcher.find();
if(foundMatch == false){
Toast.makeText( MainActivity.this, "Password must have one Numeric Value\n"
+ "\nOne Upper & Lower Case Letters\n"
+ "\nOne Special Character $ @ ! % * ? &", Toast.LENGTH_LONG ).show();
//etPW.setText("");
//etCPW.setText("");
// Two lines of code above are optional
// Also by design these fields can be set to input type Password in the XML file
etPW.requestFocus();
return ;
}
# 1 楼答案
可以使用负前瞻检查空格:
^(?!.* )
^
-从字符串开头开始匹配(?!
-开始一个负前瞻组(括号内的模式不能出现在下一个).*
-任何非换行字符,任意次后跟空格)
-关闭负前瞻组结合完整的正则表达式模式(也进行了一些清理以消除冗余):
^(?!.* )(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[!@$%&*?])[A-Za-z\\d!@$%&*?]+