[英]Checking string for 3 letters then 3 numbers
我需要能够检查一个字符串,以便其中的前 3 个字符是字母,最后 3 个字符是数字,例如像“ABC123”这样的 rego,并确保它不是“123ABC”或“1A2B3C”之类的东西
使用以下内容:
string.matches("[a-zA-Z]{3}.*[0-9]{3}");
you can use this pattern with regex:您可以将此模式与正则表达式一起使用:
([a-zA-Z][a-zA-Z][a-zA-Z][0-9][0-9][0-9])
if you have anything in between you can use:如果你有任何之间的东西,你可以使用:
([a-zA-Z][a-zA-Z][a-zA-Z].*[0-9][0-9][0-9])
try this pattern ^[A-Za-z]{3}.*[0-9]{3}$
试试这个模式
^[A-Za-z]{3}.*[0-9]{3}$
String test = "ABC123";
Matcher matcher = Pattern.compile("^[A-Za-z]{3}.*[0-9]{3}$").matcher(test);
if (matcher.find()) {
System.out.print(matcher.group());
}
output:输出:
ABC123
you can check it like this:你可以这样检查:
if (!"AB1C23".matches("^([A-Za-z]{3}[0-9]{3})")) {
System.out.println("Invalid!!");
}
\\d
matches a digit \\d
匹配一个数字
[a-zA-Z]
matches a letter [a-zA-Z]
匹配一个字母
{3}
is the quantifier that matches exactly 3 repetitions {3}
是恰好匹配 3 次重复的量词
()
group maches ()
组队
([a-zA-Z]{3})(\\\\d{3})
public static void main(String[] args) {
Matcher matcher = Pattern.compile("([a-zA-Z]{3})(\\d{3})").matcher("ABC215");
// Matcher matcher = Pattern.compile("([a-zA-Z]{3})(\\d{3})").matcher("1A2B3C"); //Macher not find :)
if (matcher.find()) {
System.out.println(matcher.group(0)); //ABC215
System.out.println(matcher.group(1)); //ABC
System.out.println(matcher.group(2)); //215
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.