【发布时间】:2015-10-07 20:05:16
【问题描述】:
我想拆分一个字符串并对正则表达式模式感到绝望。
我需要将这样的字符串:Hi I want "to split" this (String) 拆分为这样的字符串数组:
String [] array = {"Hi", "I", "want", """, "to", "split", """, "this", "(", "string", ")"};
这是我尝试过的,但它删除了分隔符。
public static void main(String[] args) {
String string = "Hi \"why should\" (this work)";
String[] array;
array = string.split("\\s"
+ "|\\s(?=\")"
+ "|\\w(?=\")"
+ "|\"(?=\\w)"
+ "|\\s(?=\\()"
+ "|\\w(?=\\))"
+ "|\\((?=\\w)");
for (String str : array) {
System.out.println(str);
}
}
结果:
Hi
why
shoul
"
this
wor
)
【问题讨论】:
-
到目前为止你尝试了什么?请给我们一些代码。
-
是的,应该是java
-
@d_amiD 你可以修复
Hi,I,want,",to,split,",this,(,string,)这不好 -
所以你想在每个空格、每个特殊字符上拆分它?你想存储特殊字符,而不是空格?
-
@Emz 是的。我想到了一些带有前瞻的东西,但这对于保留特殊字符不起作用