如何检查字符串是否具有特定模式 [英] How to check if a string is of a specific pattern

查看:108
本文介绍了如何检查字符串是否具有特定模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The user inputs any string and the program distinguishes whether the string is qualifying product ID or not.

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

The qualifying product IDs are any of string consists of two capitals and four numbers. (For example, "TV1523")

我该如何制作这个节目?

How can I make this program?

推荐答案

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

You should compare the string using a regular expression, for example:

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

str.matches("^[A-Z]{2}\\d{4}") will give you a boolean value as to whether it matches or not.

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

The regular expression works as follows:

^ 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).

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

Using this method, you can loop through any number of strings and check if they match the criteria given.

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

You should read up on regular expressions though, there are more efficient ways of storing the pattern if you are worried about performance.

这篇关于如何检查字符串是否具有特定模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆