想要在String中搜索,如果有任何特殊字符 [英] Want to search in String if there is any special characters in it
问题描述
我想搜索java字符串中的任何特殊字符。
这里是我的代码
I want to search any special char in java string. here is my code
Pattern p = Pattern.compile("^[a-zA-Z0-9 ]");
Matcher m = p.matcher("hgbs!hf862376");
boolean b = m.matches();
if (b == true)
System.out.println("sp. character is there");
但这不起作用。
任何人都可以为此建议正确的正则表达式。
我想只允许az,AZ和0-1。
But this is not working. Can any one suggest correct Regex for this. I want to allowed only a-z,A-Z and 0-1.
提前谢谢你。
推荐答案
。* [^ a-zA-Z0-9]。*
而不是 ^ [a -zA-Z0-9]
^字符类(即方括号)表示否定,所以除了列出的字符外。如果不在字符类中,则^表示字符串的开始。
您还需要在特殊字符之前或之后匹配任何内容。
因此,您的原始正则表达式只匹配 a-zA-Z0-9
中包含单个字母的字符串。
^ within character class (i.e. square brackets) mean negation, so any but the characters listed. If not within character class, ^ means the beggining of the string.
Also you need to match anything before or after the special character.
So your original regex would have matched only strings that have a single letter among a-zA-Z0-9
.
这篇关于想要在String中搜索,如果有任何特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!