我正在使用一個 Java 程式,我正在嘗試創建一個正則運算式,該運算式將匹配具有二維的任何內容,并且不匹配任何超過該維度的內容。
我還試圖指出兩個捕獲組,以便我可以分別捕獲每個維度值。必須按以下格式輸入尺寸Some number x Other number(以 分隔x)
以下是一些示例,可以更好地解釋我正在嘗試做的事情:
S (26 in x 30 in):這應該匹配并捕獲 26 和 30。20 x 40:這應該匹配并捕獲 20 和 40。Standard Size (10 x 40):這應該匹配并捕獲 10 和 40。20 x 40 x 80: 這根本不匹配。M (26 in x 30 in x 50 in): 這根本不匹配。
我已經嘗試過這個正則運算式,但它仍然認為 3 個維度是有效的:
([\d.,] ).*?[xX] ?([\d,.] ).*
uj5u.com熱心網友回復:
我認為這應該讓你得到你想要的:
^[^\d]*(\d )[^\dx]*[xX][^\dx]*(\d )[^\d]*$
可能會出現一個邊緣情況,即您的x不是兩個數字之間的分隔符。不確定這對您的用例是否有問題。
你可以看到它在這里作業regex101
uj5u.com熱心網友回復:
嘗試這個:
^(?!.* x .* x ).*?(\d )(?: [a-z] )? x (\d )
見現場演示。
由于錨定到開始的負前瞻,超過 2 個維度被阻止匹配 ^(?!.* x .* x )
uj5u.com熱心網友回復:
你可以使用運算式
^\D*(\d (?:\.\d )?)(?![\d.])[^x\d]*x[^x\d]*(\d (?:\.\d )?)(?![\d.])(?![^x\d]*x[^x\d]*\d)
演示
以下操作由正則運算式引擎執行。
^ # match beginning of the string
\D* # match 0 or more chars other than digits
( # begin capture group 1
\d # match 1 or more digits
(?: # begin non-capture group
\.\d # match a period followed by one or more digits
)? # end non-capture group and make it optional
) # end capture group group 1
(?! # begin negative lookahead
[\d.] # match a digit or period
) # end negative lookahead
[^x\d]* # match 0 or more chars other than 'x' and digits
x # match 'x'
[^x\d]* # match 0 or more chars other than 'x' and digits
( # begin capture group 2
\d # match 1 or more digits
(?: # begin non-capture group
\.\d # match a period followed by one or more digits
)? # end non-capture group and make it optional
) # end capture group group 2
(?! # begin negative lookahead
[\d.] # match a digit or period
) # end negative lookahead
(?! # begin negative lookahead
[^x\d]* # match 0 or more chars other than 'x' and digits
x # match 'x'
[^x\d]* # match 0 or more chars other than 'x' and digits
\d # match a digit
) # end negative lookahead
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/321128.html
