简体   繁体   English

检查字符串是否为长度为 1 到 5 的字母数字

[英]Check that String is alphanumeric with length 1 to 5

I have wrote the following test code snippet:我编写了以下测试代码片段:

"123".matches("\\[a-zA-Z0-9]{1,5}");

However, it returns false .但是,它返回false

Why and how to fix this?为什么以及如何解决这个问题?

By escaping the first [ , you made it a literal [ , while you wanted to define a character class (bracket expression).通过转义第一个[ ,您将其变成了文字[ ,而您想要定义一个字符类(括号表达式)。

Remove \\ :删除\\

"123".matches("[a-zA-Z0-9]{1,5}");
               ^  

See the Java demo :请参阅Java 演示

System.out.println("123".matches("[a-zA-Z0-9]{1,5}")); // = > true

Regex without \\\\ will work.没有\\\\则表达式将起作用。 You don't need to escape anything.你不需要逃避任何事情。

"123".matches("[a-zA-Z0-9]{1,5}");

You're escaping the first square bracket with the \\\\ , which means the expression between the square brackets isn't treated as a character class.您使用\\\\转义第一个方括号,这意味着方括号之间的表达式不被视为字符类。 Remove the escaping and you should be OK:删除转义,你应该没问题:

"123".matches("[a-zA-Z0-9]{1,5}"
// Here -------^

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM