2011-10-27 40 views
6

用户输入任何字符串,程序会区分字符串是否符合产品ID。如何检查字符串是否具有特定模式

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

我该如何制作此程序?

+1

...通过思考,并尝试...... –

+3

-1:听起来像作业,你应该尝试自己解决它 –

+0

亚历克斯这是不是功课。 – schizoid322

回答

25

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

str.matches("^[A-Z]{2}\\d{4}")会给你一个布尔值来判断它是否匹配。

正则表达式的工作原理如下:

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

使用这种方法,你可以通过任何数量的字符串循环,并检查它们是否符合规定的标准。

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

+1

您不会错过'$',您的'^'是不必要的。 'matcher()'方法试图匹配模式的完整输入,所以它有两个锚“内置”。 [class Matcher](http://download.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html)。无论如何+1的模式的解释。 – stema

+0

感谢您的详细解释。我非常感谢你的帮助! – schizoid322

0
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()代替:X

+0

感谢你的答案,但似乎只有'TV1523'在你的答案中是有效的。我的意思是所有的两个首都和四个数字都是有效的。 – schizoid322

+0

@ schizoid322这是一个示例,尝试自己编码一点;) –

4

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

您模式的一个例子可能是

^[A-Z]{2}\d{4}$ 

你可以看到它here on Regexr.com的好地方在线测试正则表达式。

这里是java regex tutorial那里你可以看到你如何用Java调用它们。

+0

Aaaa。我错过了$。做得好! – Ewald

+0

我真的很感谢你的回答。你的答案几乎完美! – schizoid322

相关问题