首页 > 解决方案 > 如何在不拆分字符串的情况下检查字符串是否具有某种模式?

问题描述

所以这就是问题所在。有人能告诉我正则表达式模式的样子吗?

编写一个程序,确定输入字符串是否与以下格式匹配:

格式:PRODUCT_ID.PRODUCT_CATEGORY-LOCATOR_TYPE[LOCATOR_LOT]

  • PRODUCT_ID= 始终以 # 开头,后跟 3 个零,后跟可以是 1-7 位的数值,范围为 1-9999999
  • PRODUCT_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),我认为我在这里的轨道不正确

标签: javaregex

解决方案


这是一个有效的正则表达式:

#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网站是一个非常好的工具,可以帮助您更好地理解正则表达式


推荐阅读