I want to check if a string matches a pattern of 1-2 letters, 1-4 digits, and 1 letter. (Examples: CC44C, C4444C).
我想检查字符串是否匹配1-2个字母,1-4个数字和1个字母的模式。 (例子:CC44C,C4444C)。
I understand that str.matches("^[A-Z]{2}\\d{4}[A-Z]{1}")
would match a pattern of 2 letters, 4 digits, and 1 letter exactly. (Example: CC4444C)
据我所知,str.matches(“^ [A-Z] {2} \\ d {4} [A-Z] {1}”)将完全匹配2个字母,4个数字和1个字母的模式。 (例如:CC4444C)
But how do I make it so it can match a pattern with a range (ie. 1-2 letters, 1-4 digits)?
但是我如何制作它可以匹配范围的模式(即1-2个字母,1-4个数字)?
I've tried str.matches("^[A-Z]{1-2}\\d{1-4}[A-Z]{1}")
, but it gives me the following error:
我已经尝试过str.matches(“^ [A-Z] {1-2} \\ d {1-4} [A-Z] {1}”),但它给了我以下错误:
java.util.regex.PatternSyntaxException: Unclosed counted closure near index 8
^[A-Z]{2-3}\d{1-4}[A-Z]{1}
1 个解决方案
#1
3
You need to change {1-2} to {1,2}, you could understand this as {minimun, maximum}. Please run the below example and view the result.
您需要将{1-2}更改为{1,2},您可以将其理解为{minimun,maximum}。请运行以下示例并查看结果。
public class RegularExpression {
public static void main(String[] ar) {
String str1 = "CC44C";
String str2 = "C4444C";
String str3 = "4444C";
String str4 = "SDFSD123C";
String pattern = "^[A-Z]{1,2}\\d{1,4}[A-Z]{1}";
System.out.println(str1+" matches?: "+str1.matches(pattern));
System.out.println(str2+" matches?: "+str2.matches(pattern));
System.out.println(str3+" matches?: "+str3.matches(pattern));
System.out.println(str4+" matches?: "+str4.matches(pattern));
}
}
Additionally, if you do not know the maximum, you could use {1,}.
此外,如果您不知道最大值,则可以使用{1,}。
String newPattern = "^[A-Za-z]{1,}\\d{1,}[A-Za-z]{1,}";
You could change the pattern above to newPattern and view the result.
您可以将上面的模式更改为newPattern并查看结果。
Hopefully this could help you :)
希望这可以帮助你:)
#1
3
You need to change {1-2} to {1,2}, you could understand this as {minimun, maximum}. Please run the below example and view the result.
您需要将{1-2}更改为{1,2},您可以将其理解为{minimun,maximum}。请运行以下示例并查看结果。
public class RegularExpression {
public static void main(String[] ar) {
String str1 = "CC44C";
String str2 = "C4444C";
String str3 = "4444C";
String str4 = "SDFSD123C";
String pattern = "^[A-Z]{1,2}\\d{1,4}[A-Z]{1}";
System.out.println(str1+" matches?: "+str1.matches(pattern));
System.out.println(str2+" matches?: "+str2.matches(pattern));
System.out.println(str3+" matches?: "+str3.matches(pattern));
System.out.println(str4+" matches?: "+str4.matches(pattern));
}
}
Additionally, if you do not know the maximum, you could use {1,}.
此外,如果您不知道最大值,则可以使用{1,}。
String newPattern = "^[A-Za-z]{1,}\\d{1,}[A-Za-z]{1,}";
You could change the pattern above to newPattern and view the result.
您可以将上面的模式更改为newPattern并查看结果。
Hopefully this could help you :)
希望这可以帮助你:)