<分区>
用户输入任意字符串,程序判断该字符串是否为合格产品ID。
符合条件的产品 ID 是由两个大写字母和四个数字组成的任意字符串。 (例如,“TV1523”)
如何制作这个程序?
<分区>
用户输入任意字符串,程序判断该字符串是否为合格产品ID。
符合条件的产品 ID 是由两个大写字母和四个数字组成的任意字符串。 (例如,“TV1523”)
如何制作这个程序?
最佳答案
您应该使用正则表达式比较字符串,例如:
str.matches("^[A-Z]{2}\\d{4}")
会给你一个 boolean 值,判断它是否匹配。
正则表达式的工作原理如下:
^ 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).
使用此方法,您可以遍历任意数量的字符串并检查它们是否符合给定的条件。
不过,您应该仔细阅读正则表达式,如果您担心性能,还有更有效的方式来存储模式。
关于java - 如何检查字符串是否具有特定模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7914069/