[英]Regex for splitting a string delimited by | when not enclosed on double quotes
我需要一個正則表達式來計算java中管道分隔字符串中的列數。 列數據將始終用雙引號括起來,否則將為空。
例如:
"1234"|"Name"||"Some description with ||| in it"|"Last Column"
以上內容應計為5列,包括“名稱”列后的一列空列。
謝謝
這是一種方法:
String input =
"\"1234\"|\"Name\"||\"Some description with ||| in it\"|\"Last Column\"";
// \_______/ \______/\/\_________________________________/ \_____________/
// 1 2 3 4 5
int cols = input.replaceAll("\"[^\"]*\"", "") // remove "..."
.replaceAll("[^|]", "") // remove anything else than |
.length() + 1; // Count the remaining |, add 1
System.out.println(cols); // 5
IMO雖然不是很強大。 例如,如果您計划處理轉義引號,我建議不要使用正則表達式。
稍微改進了aioobe答案中的表達:
int cols = input.replaceAll("\"(?:[^\"\\]+|\\.)*\"|[^|]+", "")
.length() + 1;
處理引號中的轉義,並使用單個表達式刪除除分隔符之外的所有內容。
這是我用了一段時間的正則表達式,它還處理轉義的引號和轉義的分隔符 。 它可能對您的要求(計數列)有點過分,但也許它將幫助您或將來的其他人進行解析。
(?<=^|(?<!\\)\|)(\".*?(?<=[^\\])\"|.*?(?<!\\(?=\|))(?=")?|)(?=\||$)
and broken down as:
(?<=^|(?<!\\)\|) // look behind to make sure the token starts with the start anchor (first token) or a delimiter (but not an escaped delimiter)
( // start of capture group 1
\".*?(?<=[^\\])\" // a token bounded by quotes
| // OR
.*?(?<!\\(?=\|))(?=")? // a token not bounded by quotes, any characters up to the delimiter (unless escaped)
| // OR
// empty token
) // end of capture group 1
(?=\||$) // look ahead to make sure the token is followed by either a delimiter or the end anchor (last token)
when you actually use it it'll have to be escaped as:
(?<=^|(?<!\\\\)\\|)(\\\".*?(?<=[^\\\\])\\\"|.*?(?<!\\\\(?=\\|))(?=\")?|)(?=\\||$)
這很復雜,但是有這種瘋狂的方法:如果在行的開頭或結尾的列是空的,分隔的引號在奇數位置,行或列以轉義開始或結束,我搜索的其他正則表達式將會失敗分隔符,以及一堆其他邊緣情況。
您使用管道作為分隔符的事實使得此正則表達式更難以閱讀/理解。 提示是你自己看到一個管道“|”,它是正則表達式中的一個條件OR,當它被轉義為“\\ |”時,它就是你的分隔符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.