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

标签 java regex

<分区>

用户输入任意字符串,程序判断该字符串是否为合格产品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/

相关文章:

java - 在这种情况下使用synchronized() 意味着什么?

java - Spring运行时错误,没有为实体指定标识符:

java - Apache Shiro 用于桌面应用程序?

Java Scanner hasNext() 字符串正则表达式验证

javascript - 使用正则表达式将字符串转换为 JavaScript 数组

regex - 识别特殊字符

javascript - 替换两个标记之间的 URL 中的 ID

java - 在 Parcelable 中进行包裹读/写操作时,变量顺序是否重要?

regex - 可以在范围内运行 Regex-Replace 而不是循环遍历 Excel 中的单元格吗?

java - 当用户向下滚动并到达数据集末尾时更新数据集的最佳方法是什么?