简体   繁体   English

正则表达式模式检查字符串是否没有特殊字符 - Java

[英]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我使用了如下的正则表达式模式,但它们都不起作用

  1. String regex = "^[a-zA-Z0-9_-.]*$";

  2. String regex = "+/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/i";

  3. String regex = "^([-.A-Za-z0-9]){1,20}$";

  4. 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.如果我将-移到最后,我可以成功创建一个应该工作的模式。

You missed a \ before the - .您在-之前错过了一个\ You should use你应该使用

^[a-zA-Z0-9_\-.]*$

See the demo查看演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Java中,我应该使用哪种正则表达式来检查仅包含数字和2个特殊字符(-和,)的字符串? - What regex should I use to check a string only has numbers and 2 special characters ( - and , ) in Java? 正则表达式检查字符串是否以“+”、“-”、“=”或“@”等特殊字符开头 Java - Regex to check if a String starts with special characters like "+" , "-" , "=" or "@" Java 如何在java中检查字符串是否有超过2的连续特殊字符? - How to check if the string has consequitive special characters more than 2 in java? 正则表达式模式可排除字符串中的数字和特殊字符 - Regex pattern to exclude numbers and special characters in a string 如何在Java的正则表达式模式中转义特殊字符? - How to escape special characters in a regex pattern in java? Java:字符串模式:如何为具有特殊字符的所有字符字符指定正则表达式 - Java: String pattern : how to specify regex for all alpha characters with special characters 使用正则表达式检查特殊字符Java - Using a regex to check for special characters java Java正则表达式用特殊字符替换字符串 - Java regex replace string with special characters Java正则表达式不允许字符串特殊字符 - Java Regex to not allow String Special Characters Java正则表达式-拆分带前导特殊字符的字符串 - Java regex - split string with leading special characters
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM