[英]How do I check if a string is of a certain pattern without splitting it up?
所以這就是問題所在。 有人能告訴我正則表達式模式的樣子嗎?
編寫一個程序,確定輸入字符串是否與以下格式匹配:
格式:
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所有其他格式字符都是文字字符
如果匹配則返回真,否則返回假。
這是 function 聲明:
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網站是一個非常好的工具,可以幫助您更好地理解正則表達式
我認為您應該嘗試確定每個元素的模式,然后在它們之間合並。 我能夠識別每個部分,但我不明白最后一個:
所有其他格式字符都是文字字符。
無論如何,我希望這會對你有所幫助。 閱讀代碼中包含的注釋。
public boolean checkPattern(String s){
if(s.matches("#000[1-9]{1,7}.[A-Z]{1,4}-([X-Z])\\[[1-9]{1,2}\\]")) return true;
else return false;
// #000[1-9]{1,7} ==> matches PRODUCT_ID
//. ==> to simply match the point
// [A-Z]{1,4} ==> PRODUCT_CATEGORY
//- ==> to simply match this symbol
// ([X-Z]) ==> LOCATOR_TYPE
// \\[ Use the double slash here so the [ symbol becomes recognized
// [1-9]{1,2} ==> LOCATOR_LOT
// \\]
// String s="#000123.ABC-X[99]"; this is a test example I used.
}
在使用正則表達式時,您必須仔細閱讀您的要求以及預定義的正則表達式運算符和工具。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.