如果字符串没有被这种括号[]
包围,如何用空格分割字符串?因此字符串" book [new interesting book] buy it "
应该分成
book
new interesting book
buy
it
或
book
[new interesting book]
buy
it
谢谢!
答案 0 :(得分:3)
它必须是正则表达式吗?您可以通过计算空格前的多少个括号来确定是否应该用新的线标记替换该空格,从而一次迭代。
String data="book [new [interesting] book] buy it";
StringBuilder buffer=new StringBuilder();
int bracketCounter=0;
for (char c:data.toCharArray()){
if (c=='[') bracketCounter++;
if (c==']') bracketCounter--;
if (c==' ' && bracketCounter==0)
buffer.append("\n");
else
buffer.append(c);
}
System.out.println(buffer);
输出:
book
[new [interesting] book]
buy
it
答案 1 :(得分:2)
这里使用String.split()
很困难,因为很难区分括号内的空格和它们之外的空格。相反,不断Matcher.find()
反对你的字符串,直到你用完令牌为止。
List<String> tokens = new ArrayList<String>();
Pattern p = Pattern.compile("\\s*(\\[.*\\]|[^\\s]+)\\s*");
Matcher m = p.matcher(" book [new interesting book] buy it ");
while (m.find()) {
tokens.add(m.group());
}
System.out.println(tokens);
// Prints: [ book , [new interesting book] , buy , it ]
上面的正则表达式忽略了前导和尾随空格,并且抓取:(1)任何东西,如果它在括号内或(2)任何非空格序列。
答案 2 :(得分:2)
我已经改变了一点@ cheeken的回应,只是为了改善它一点点。由于代码格式化,我决定将其包含在答案中:
List<String> tokens = new ArrayList<String>();
Pattern p = Pattern.compile("\\s*(\\[.*\\]|[\\S]*)\\s*");
Matcher m = p.matcher(" book [new interesting book] buy it ");
while (m.find()) {
if (!m.group().matches("\\s*")) {
tokens.add(m.group());
}
}
我改变了模式的第二部分,以便使用预定义的类\ S而不是他的否定,并且我针对空字符串测试了模式,以避免包含他的答案允许的初始和最终空格。
答案 3 :(得分:0)
String input = "foo [bar bar] foo";
Pattern p = Pattern.compile("\[|\]");
String[] s = p.split(input);
现在我们左边有[,括号里面的部分和右边的部分]。 现在你可以通过这些部分(如果需要)进一步拆分它们。