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

sch*_*322 12 java regex

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

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

我该如何制作这个节目?

Ewa*_*ald 35

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

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).
Run Code Online (Sandbox Code Playgroud)

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

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

  • 你没有错过`$`,你的`^` 是不必要的。`matcher()` 方法尝试将完整的输入与模式匹配,因此它“内置”了两个锚点。[类匹配器](http://download.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html)。无论如何+1来解释模式。 (2认同)

ste*_*ema 5

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

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

^[A-Z]{2}\d{4}$
Run Code Online (Sandbox Code Playgroud)

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

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