[英]Regex pattern to check if string has no special characters - Java
I want to check if a string contains no special characters like @, $ etc and include only alphanumerics and special characters like "-", "."我想检查一个字符串是否不包含 @、$ 等特殊字符,并且只包含字母数字和特殊字符,如“-”、“。”
I have used regex pattern as below, but none of them is working我使用了如下的正则表达式模式,但它们都不起作用
String regex = "^[a-zA-Z0-9_-.]*$";
String regex = "+/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/i";
String regex = "^([-.A-Za-z0-9]){1,20}$";
String regex = "^[a-zA-Z0-9_-.]*";
if (r.getTest().matches(regex)){}
Edit:编辑:
The regex in the answers is working fine, but when added it as condition in the code, the code is always returning false, saying it contains special characters, when all I have in the string are alphanumerics, and dots(.).答案中的正则表达式工作正常,但是当将其作为条件添加到代码中时,代码总是返回 false,表示它包含特殊字符,而我在字符串中只有字母数字和点(。)。
None of them is working.他们都没有工作。 Any help is much appreciated.
任何帮助深表感谢。
I see one big issue with your first regex, and that's the -
.我看到您的第一个正则表达式存在一个大问题,那就是
-
。 Between [
and ]
, every -
means a range except if it's escaped, or if it's the first or last character.在
[
和]
之间,每个-
表示一个范围,除非它被转义,或者它是第一个或最后一个字符。 With what you have now, I get an exception:有了你现在所拥有的,我得到了一个例外:
Exception java.util.regex.PatternSyntaxException: Illegal character range near index 13
^[a-zA-Z0-9_-.]*$
If I move the -
to the end, I can successfully create a pattern that should work.如果我将
-
移到最后,我可以成功创建一个应该工作的模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.