![](/img/trans.png)
[英]How to Split a String on mathematical operators as delimiters but escape operators inside quotes (in 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.