簡體   English   中英

用Java分割字符串,保留定界符,包括引號內的項目

[英]Split string in Java, retain delimiters including items inside quotes

我有一個.txt輸入文件,如下所示:

Start "String" (100, 100) Test One:
  Nextline 10;
  Test Second Third(2, 4, 2, 4):
    String "7";
    String "8";
    Test "";
  End;
End.

我打算將此文件讀為一個字符串,然后根據某些定界符將其拆分。 使用此代碼,我幾乎達到了所需的輸出:

String tr=  entireFile.replaceAll("\\s+", "");

String[] input = tr.split("(?<=[(,):;.])|(?=[(,):;.])|(?=\\p{Upper})");

我當前的輸出是:

Start"
String"
(
100
,
100
)
Test
One
:
Nextline10
;
Test
Second
Third
(
2
,
4
,
2
,
4
)
:
String"7"
;
String"8"
;
Test""
;
End
;
End
.

但是,我在將引號內或僅將單引號“”中的項目作為單獨的標記時遇到麻煩。 因此,“ String”和“ 7”和“”應該都放在單獨的行上。 有沒有辦法用正則表達式做到這一點? 我的預期輸出如下,感謝您的幫助。

Start
"String"
(
100
,
100
)
Test
One
:
Nextline
10
;
Test
Second
Third
(
2
,
4
,
2
,
4
)
:
String
"7"
;
String
"8"
;
Test
""
;
End
;
End
.

這是我想出的正則表達式:

String[] input = entireFile.split(
        "\\s+|" +           // Splits on whitespace or 
        "(?<=\\()|" +         // splits on the positive lookbehind ( or
        "(?=[,).:;])|" +  // splits on any of the positive lookaheads ,).:; or
        "((?<!\\s)(?=\\())"); // splits on the positive lookahead ( with a negative lookbehind whitespace

要了解所有積極/消極的先行/后退術語,請看一下此答案

請注意,您應該將此拆分直接應用於輸入文件,而不要刪除空格,也就是刪除以下行:

String tr=  entireFile.replaceAll("\\s+", "");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM