我有一个 .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
要了解所有正/负前瞻/后瞻术语,请查看 this answer .
请注意,您应该将此分割直接应用于输入文件,而不删除空格,也就是删除此行:
String tr= entireFile.replaceAll("\\s+", "");
关于java - 在Java中分割字符串,保留分隔符,包括引号内的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21446764/