如何检查字符串是否具有特定模式

用户输入任何字符串,程序会区分字符串是否符合条件的产品ID。

符合条件的产品ID是由两个大写字母和四个数字组成的字符串中的任何一个。 (例如,“TV1523”)

我怎样才能制作这个节目?

您应该使用正则表达式比较字符串,例如:

str.matches("^[AZ]{2}\\d{4}")将给出一个关于它是否匹配的布尔值。

正则表达式的工作方式如下:

 ^ Indicates that the following pattern needs to appear at the beginning of the string. [AZ] Indicates that the uppercase letters AZ are required. {2} Indicates that the preceding pattern is repeated twice (two AZ characters). \\d Indicates you expect a digit (0-9) {4} Indicates the the preceding pattern is expected four times (4 digits). 

使用此方法,您可以遍历任意数量的字符串并检查它们是否与给定的条件匹配。

您应该阅读正则表达式,如果您担心性能,可以使用更有效的方式存储模式。

你应该仔细看看正则表达式。 教程例如在regular-expressions.info上 。

你的模式的一个例子可能是

 ^[AZ]{2}\d{4}$ 

你可以在Regexr.com上看到它是一个在线测试正则表达式的好地方。

这里是java正则表达式教程 ,你可以看到你如何用Java调用它们。

 public static void main(String[] args) throws Exception { String id = "TV1523"; BufferedReader br = new BufferedReader((new InputStreamReader(System.in))); String tocompare = br.readLine(); if(tocompare.equals(id)) { //do stuff 

类似的东西,除了你可能用魔杖把readLine()包含在try catch中:x