java 在java中使用正则表达式检查字符串中的特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48031098/
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
Check for special characters in a string using regex in java
提问by Stackover67
How to check for special chars in a string? I am checking for just empty spaces using regex but when i enter special chars it's considering them as space. Below is my code
如何检查字符串中的特殊字符?我正在使用正则表达式检查空格,但是当我输入特殊字符时,它会将它们视为空格。下面是我的代码
private boolean emptySpacecheck(String msg){
return msg.matches(".*\w.*");
}
How to check for special chars?
如何检查特殊字符?
回答by Mahesh Vayak
You can use Pattern matcher for check special character and you can check below example:
您可以使用模式匹配器来检查特殊字符,您可以检查以下示例:
Pattern regex = Pattern.compile("[$&+,:;=\\?@#|/'<>.^*()%!-]");
if (regex.matcher(your_string).find()) {
Log.d("TTT, "SPECIAL CHARS FOUND");
return;
}
Hope this helps you...if you need any help you can ask
希望这对你有帮助......如果你需要任何帮助,你可以问
回答by Fenil Patel
An easy way is to check if a string has any non-alphanumeric characters.
一种简单的方法是检查字符串是否包含任何非字母数字字符。
TRY THIS,
试试这个,
StringChecker.java
字符串检查器
public class StringChecker {
public static void main(String[] args) {
String str = "abc$def^ghi#jkl";
Pattern p = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);
System.out.println(str);
int count = 0;
while (m.find()) {
count = count+1;
System.out.println("position " + m.start() + ": " + str.charAt(m.start()));
}
System.out.println("There are " + count + " special characters");
}
}
And you get the result look like below:
你得到的结果如下所示:
$ java SpecialChars
abc$def^ghi#jkl
position 3: $
position 7: ^
position 11: #
There are 3 special characters
You can pass your own patterns as param in compile methods as per your needs to checking special characters:
Pattern.compile("[$&+,:;=\\?@#|/'<>.^*()%!-]");
您可以根据需要在编译方法中将自己的模式作为参数传递以检查特殊字符:
Pattern.compile("[$&+,:;=\\?@#|/'<>.^*()%!-]");
回答by CoderCroc
...when i enter special chars it's considering them as space.
...当我输入特殊字符时,它会将它们视为空格。
Which means you only want to check whether String contains space or not.
这意味着您只想检查 String 是否包含空格。
You don't need regular expression to check for space. You can simply call String#contains
method.
您不需要正则表达式来检查空间。您可以简单地调用String#contains
方法。
private boolean emptySpacecheck(String msg){
return msg != null && msg.contains(" ");
}
回答by frogatto
You can use the following RegExp:
您可以使用以下正则表达式:
private boolean emptySpacecheck(String msg){
return msg.matches(".*\s+.*");
}
\s
matches with these characters:[ \t\n\x0B\f\r]
\s
与这些字符匹配:[ \t\n\x0B\f\r]
Try it online: https://regex101.com/r/GztOoI/1