java Java检测字符串中的特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10902911/
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
Java detect special characters in a string
提问by Eric
I use regex
我使用正则表达式
r="[^A-Za-z0-9]+";
to detect if a string has one or more chars other than letters and digits;
检测一个字符串是否有一个或多个字母和数字以外的字符;
Then I tried the following:
然后我尝试了以下方法:
Pattern.compile(r).matcher(p).find();
I tested:
我测试过:
! @ # $ % ^ & * ( ) + =- [ ] \ ' ; , . / { } | " : < > ? ~ _ `
Most of the time, it works except backsplash \ and caret ^.
大多数情况下,除了反斜杠 \ 和插入符号 ^ 外,它都可以工作。
e.g.
例如
String p = "abcAsd10^" (return false)
String p = "abcAsd10\" (return false)
Anything I miss?
我有什么想念的吗?
回答by jahroy
The following code prints "Found: true" when I compile and run it:
当我编译并运行它时,以下代码打印“Found:true”:
class T
{
public static void main (String [] args)
{
String thePattern = "[^A-Za-z0-9]+";
String theInput = "abskKel35^";
boolean isFound = Pattern.compile(thePattern).matcher(theInput).find();
System.out.println("Found: " + isFound);
}
}
Not sure why you would see a different result...
不知道为什么你会看到不同的结果......
回答by baby boom
When I run this code on my machine it prints true..
当我在我的机器上运行此代码时,它会打印 true..
String r="[^A-Za-z0-9]+";
String p = "abcAsd10\" ;
Matcher m = Pattern.compile(r).matcher(p);
System.out.println(m.find());
true
真的
回答by buckley
Shouldn't that be:
不应该是:
r="[^A-Za-z0-9]+";
In your question you write a_z (underscore)
在你的问题中你写 a_z (下划线)
回答by Paul Vargas
回答by Robert de W
Try quoting your input into the matcher.
尝试将您的输入引用到匹配器中。
Pattern.quote(p)
回答by Eric
Sorry, I had
对不起,我有
r="[^A-za-z0-9]+"; (with little "z", i.e. A-z).
That causes returning "false". But why it works with other special chars except backsplash \ and caret ^?
这会导致返回“false”。但是为什么它可以与除反斜杠 \ 和插入符号 ^ 之外的其他特殊字符一起使用?
回答by elias
Simply do:
简单地做:
p.matches(".*\W.*"); //return true if contains one or more special character