java Java正则表达式验证特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7822577/
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 regex validating special chars
提问by brakebg
This seems like a well known title, but I am really facing a problem in this.
这似乎是一个众所周知的标题,但我确实面临着这个问题。
Here is what I have and what I've done so far.
这是我所拥有的以及到目前为止我所做的。
I have validate input string, these chars are not allowed :
我有验证输入字符串,这些字符是不允许的:
&%$##@!~
&%$##@!~
So I coded it like this:
所以我这样编码:
String REGEX = "^[&%$##@!~]";
String username= "jhgjhgjh.#";
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(username);
if (matcher.matches()) {
System.out.println("matched");
}
回答by Narendra Yadala
Change your first line of code like this
像这样改变你的第一行代码
String REGEX = "[^&%$#@!~]*";
And it should work fine. ^
outside the character class denotes start of line. ^
inside a character class []
means a negation of the characters inside the character class. And, if you don't want to match empty usernames, then use this regex
它应该可以正常工作。^
在字符类之外表示行的开始。^
字符类内部[]
意味着字符类内部字符的否定。而且,如果您不想匹配空用户名,请使用此正则表达式
String REGEX = "[^&%$#@!~]+";
回答by Kent
i think you want this:
我想你想要这个:
[^&%$##@!~]*
回答by smp7d
To match a valid input:
匹配一个有效的输入:
String REGEX = "[^&%$#@!~]*";
To match an invalid input:
匹配无效输入:
String REGEX = ".*[&%$#@!~]+.*";