java - 如何在不拆分字符串的情况下检查字符串是否具有某种模式?

标签 java regex

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

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-9999999
  • PRODUCT_CATEGORY = 1-4 uppercase alphabetic characters
  • LOCATOR_TYPE = a single uppercase X, Y or Z character
  • LOCATOR_LOT = 1-2 numeric digits, in the range 1-99

All 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/

相关文章:

java - Java AsyncTask 的使用

java - java内部递归正则表达式

.net - 从youtube链接获取youtube嵌入视频代码?

javascript - javascript错误中的startwith

c# - 解析邮件地址的正则表达式

java - 像平常使用ExecutorService一样使用ForkJoinPool是否有益

java - 如何将主机名附加到 log4j.xml 中的日志文件

java - 我不明白为什么我制作的类(class)不起作用

JavaScript 正则表达式解析 URL 数组

java - 在 JFrame 或 JPanel 上重设 X11 窗口?