3 回答

TA貢獻1827條經驗 獲得超9個贊
您的正則表達式分析:
"?([\\d]+(\\.[\\d]{2})?\\|([A-Z]{2}){1})(,[A-Z]{2})*\\s(\\\".+\\\")?$"
首先,讓我們將 Java 字符串文字反轉義為實際的正則表達式字符串:
?([\d]+(\.[\d]{2})?\|([A-Z]{2}){1})(,[A-Z]{2})*\s(\".+\")?$
現在讓我們把它分開:
? Incorrect character '?', should be '^'
Match start of input, but your input starts with '['
(
[\d]+ The '[]' is superfluous, use '\d+'
(\.[\d]{2})? Don't capture this, use '(?:X)?'
\|
([A-Z]{2}){1} The '{1}` is superfluous, and don't capture just this
) You're capturing too much. Move back to before '\|'
(,[A-Z]{2})* Will only capture last ',XX'.
Use a capture group around all the letters, then split that on ','
\s
(\".+\")? No need to escape '"', and only capture the content
$ Match end of input, but your input ends with ']'
因此,清理后它將是:
^\[
(
\d+
(?:\.[\d]{2})?
)
\|
(
[A-Z]{2}
(?:,[A-Z]{2})*
)
\s
(?:"(.+)")?
\]$
一起回來:
^\[(\d+(?:\.[\d]{2})?)\|([A-Z]{2}(?:,[A-Z]{2})*)\s(?:"(.+)")?\]$
使用[15.00|GR,LQ,MD "Uber"]
將捕獲的輸入:
15.00
- 全數GR,LQ,MD
-split(",")
用于獲取數組{ "GR", "LQ", "MD" }
Uber
- 只是沒有引號的文字
請參閱regex101.com 上的演示。

TA貢獻1847條經驗 獲得超11個贊
第一個字符是 a?
而不是^
。除此之外,您應該將第一組更改([\d]+(\.[\d]{2})?)
為 get only15.00
和 not 15.00|GR
。
完整示例如下所示:
Pattern.compile("^([\\d]+(\\.[\\d]{2})?)\\|(([A-Z]{2})(,[A-Z]{2})*)\\s(\".+\")?$");

TA貢獻1835條經驗 獲得超7個贊
有兩個主要問題。
該
?
字符是重音抑揚符而不是^
插入符號。您沒有在正則表達式中包含方括號。
一個可能的解決方案可能是這樣的
Pattern.compile("^\\[(?<number>[\\d]+(?>\\.[\\d]{2})?)\\|(?<codes>(?>[A-Z]{2},?)+)(?>\\s\\\"(?<comment>.+)\\\")?\\]$");
該解決方案還命名了捕獲組,這使得指定您希望從哪個組獲取價值變得更好。https://regex101.com/r/HEboNf/2
所有三個 2 字母代碼都分組在一個捕獲組中,您可以在代碼中用逗號分隔它們。
添加回答
舉報