blu*_*lue 69 java string special-characters
如何检查String是否包含特殊字符,如:
[,],{,},{,),*,|,:,>,
Run Code Online (Sandbox Code Playgroud)
r3z*_*n1k 116
Pattern p = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("I am a string");
boolean b = m.find();
if (b)
System.out.println("There is a special character in my string");
Run Code Online (Sandbox Code Playgroud)
小智 21
您可以使用以下代码从字符串中检测特殊字符.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DetectSpecial{
public int getSpecialCharacterCount(String s) {
if (s == null || s.trim().isEmpty()) {
System.out.println("Incorrect format of string");
return 0;
}
Pattern p = Pattern.compile("[^A-Za-z0-9]");
Matcher m = p.matcher(s);
// boolean b = m.matches();
boolean b = m.find();
if (b)
System.out.println("There is a special character in my string ");
else
System.out.println("There is no special char.");
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
Pir*_*hah 11
如果您想在密码中包含至少8位数字的字母,特殊字符和数字,那么使用此代码,它可以正常工作
public static boolean Password_Validation(String password)
{
if(password.length()>=8)
{
Pattern letter = Pattern.compile("[a-zA-z]");
Pattern digit = Pattern.compile("[0-9]");
Pattern special = Pattern.compile ("[!@#$%&*()_+=|<>?{}\\[\\]~-]");
//Pattern eight = Pattern.compile (".{8}");
Matcher hasLetter = letter.matcher(password);
Matcher hasDigit = digit.matcher(password);
Matcher hasSpecial = special.matcher(password);
return hasLetter.find() && hasDigit.find() && hasSpecial.find();
}
else
return false;
}
Run Code Online (Sandbox Code Playgroud)
你究竟称之为"特殊角色"?如果您的意思是"任何不是字母数字的东西",您可以使用org.apache.commons.lang.StringUtils类(方法IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable).
如果它不是那么简单,你可以使用一个正则表达式来定义你接受的确切字符列表,并将字符串与它匹配.
一切都取决于你所说的"特殊".在正则表达式中,您可以指定
我怀疑后者就是你的意思.但如果不使用[]列表来准确指定您想要的内容.
看看java.lang.Character课程.它有一些测试方法,你可以找到一个适合你的需求.
示例:Character.isSpaceChar(c)或!Character.isJavaLetter(c)
这已在 android 7.0 到 android 10.0 中进行了测试,并且可以正常工作
使用此代码检查字符串是否包含特殊字符和数字:
name = firstname.getText().toString(); //name is the variable that holds the string value
Pattern special= Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Pattern number = Pattern.compile("[0-9]", Pattern.CASE_INSENSITIVE);
Matcher matcher = special.matcher(name);
Matcher matcherNumber = number.matcher(name);
boolean constainsSymbols = matcher.find();
boolean containsNumber = matcherNumber.find();
if(constainsSymbols == true){
//string contains special symbol/character
}
else if(containsNumber == true){
//string contains numbers
}
else{
//string doesn't contain special characters or numbers
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
290716 次 |
| 最近记录: |