我需要能够检查一个字符串,以便其中的前 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}$
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
[a-zA-Z]
matches a letter
{3}
is the quantifier that matches exactly 3 repetitions
()
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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.