java - 如何在不拆分字符串的情况下检查字符串是否具有某种模式?
问题描述
所以这就是问题所在。有人能告诉我正则表达式模式的样子吗?
编写一个程序,确定输入字符串是否与以下格式匹配:
格式:
PRODUCT_ID.PRODUCT_CATEGORY-LOCATOR_TYPE[LOCATOR_LOT]
PRODUCT_ID
= 始终以 # 开头,后跟 3 个零,后跟可以是 1-7 位的数值,范围为 1-9999999PRODUCT_CATEGORY
= 1-4 个大写字母字符LOCATOR_TYPE
= 单个大写 X、Y 或 Z 字符LOCATOR_LOT
= 1-2 位数字,范围 1-99所有其他格式字符都是文字字符
如果匹配则返回真,否则返回假。
这是函数声明:
public boolean checkPattern(String s){
}
我尝试拆分字符串,然后检查每个字符,但它变得非常复杂。
这是我到目前为止的正则表达式:
String regex = "#000^([1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9])$";
这是我开始的东西,但它又长又复杂,甚至不完整(仅检查产品 id),我认为我在这里的轨道不正确
解决方案
这是一个有效的正则表达式:
#000[1-9]\d{0,6}\.[A-Z]{1,4}\-[XYZ]\[[1-9]\d?\]
这是一个细分:
#000 # match the literal characters, #000
[1-9] # any digit 1 to 9 (to ensure there are no preceding zeroes)
\d # any digit character; equivalent to [0-9]
{0,6} # perform the preceding match (\d) anywhere from 0 to 6 times
# (0,6 instead of 1,7 because we already matched the first digit above)
\. # match a dot character. Must be escaped with a backslash \ as
# the unescaped dot will match *anything* in regex otherwise.
[A-Z] # any uppercase alphabetic character.
{1,4} # will repeat the preceding match anywhere from 1 to 4 times.
\- # match a hyphen character. escaping is optional here.
[XYZ] # any of X, Y, or Z.
\[ # a literal [ character. Must be escaped.
[1-9] # matches 1 to 9
\d # any digit; equivalent to [0-9]
? # Makes the preceding match optional. Equivalent to {0,1}
\] # a literal ] character. Must be escaped.
其他注意事项:
RegExr.com网站是一个非常好的工具,可以帮助您更好地理解正则表达式
推荐阅读
- text-mining - word2vec 用于文档分类
- javascript - 使用 PHP 发送表单输入值以在下一页的列表中选择一个选项
- r - KableExtra 和 knitr:解析错误(文本 = x,srcfile = src):意外'='
- angular - 从Angular 4中的另一个组件访问组件方法
- java - 尝试添加水平对齐的多个视图,同时垂直添加相同的视图
- java - 为什么我不能调试 Proxy.newProxyInstance 方法?
- javascript - 如何在提示中将 HTML 格式的用户输入转换为文本
- winapi - 调用GetDC(NULL)返回什么类型的DC?
- python - 在使用 jupyter notebook 的 python 中,我如何取 1 行有 100 多列并使用关键字将其拆分为第二行?
- mysql - MySQL GROUP BY 函数有时会奇怪地跳过