所以这就是问题所在。有人可以告诉我正则表达式模式是什么样子吗?
Write a program that determines if the input string matches the following format:
Format:
PRODUCT_ID.PRODUCT_CATEGORY-LOCATOR_TYPE[LOCATOR_LOT]
PRODUCT_ID
= always starts with # followed by 3 zeros, followed by a numeric value that can be 1-7 digits, in the range 1-9999999PRODUCT_CATEGORY
= 1-4 uppercase alphabetic charactersLOCATOR_TYPE
= a single uppercase X, Y or Z characterLOCATOR_LOT
= 1-2 numeric digits, in the range 1-99All other format characters are the literal characters
Return true if it matches and false otherwise.
这是函数声明:
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 是一个非常好的工具,可以帮助您更好地理解正则表达式。
关于java - 如何在不拆分字符串的情况下检查字符串是否具有某种模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58771690/