String s = "Robert - Jones \" hello world\" + good hello";结果应该为5个单元:Robert
Jones
hello world
good
hello解析例如上面这样的字符串,分割符为空格,+, -。
双引号内部视为一个整体。
多余空格不计。比如 "+ good" = "+good"。
需要知道每个单元前的分割符,拿以上例子来说,第二个单元Jones,我要知道前面是 - 号分割符。第三个hello world,我要知道前面是空格分割符。请教大家,程序怎么写呢》》》》
Jones
hello world
good
hello解析例如上面这样的字符串,分割符为空格,+, -。
双引号内部视为一个整体。
多余空格不计。比如 "+ good" = "+good"。
需要知道每个单元前的分割符,拿以上例子来说,第二个单元Jones,我要知道前面是 - 号分割符。第三个hello world,我要知道前面是空格分割符。请教大家,程序怎么写呢》》》》
String s = "Robert - Jones \" hello world\" + good hello";
List<String> tokens = new ArrayList<String>();
String aToken = "";
boolean quotAppeared = false;
for (char c: s.toCharArray()){
if (c=='"')
if (quotAppeared){
quotAppeared = false;
if (aToken.length()!=0) tokens.add(aToken);
aToken = "";
}else{
quotAppeared = true;
}
else if (quotAppeared) aToken+=c;
else if (c==' '||c=='+'||c=='-'){
if (aToken.length()!=0) tokens.add(aToken);
aToken = "";
}else aToken += c;
}
if (aToken.length()!=0) tokens.add(aToken);
for (String s1: tokens)
System.out.println(s1);
应该可以用正则。
for (String t : s.split("\\W+")) {
System.out.println(t);
}
我想这个应该会对你有帮助
//结果为0
System.out.println(str.split(",").length);
String str = "1,,2";
//结果为3
System.out.println(str.split(",").length);我也有同样的问题
怎么输出时0的
有什么办法解决
String s = "Robert - Jones \" hello world\" + good hello";
Matcher matcher = Pattern.compile("(\\s*\\-\\s*|\\s*\\+\\s*|\\s*\"\\s*)+").matcher(s);
int ws = 0;
while (matcher.find()) {
System.out.println(matcher.group());
System.out.println(s.substring(ws, matcher.start()));
ws = matcher.end();
}
System.out.println(s.substring(ws));
*String s = "Robert - Jones \" hello world\" + good hello";结果应该为5个单元:Robert
Jones
hello world
good
hello解析例如上面这样的字符串,分割符为空格,+, -。
双引号内部视为一个整体。
多余空格不计。比如 "+ good" = "+good"。
需要知道每个单元前的分割符,拿以上例子来说,第二个单元Jones,我要知道前面是 - 号分割符。第三个hello world,我要知道前面是空格分割符。请教大家,程序怎么写呢》》》》
*/import java.util.regex.Matcher;
import java.util.regex.Pattern;public class Test{
public static void main(String[] args){
String content = "Robert - Jones \" hello world\" + good hello";
process(content);
} private static void process(String content){
String regex = "^([^\" +-]+|\"[^\"]+\")([+ -]*)(.*)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(content);
String c = null;
String sign = null;
while(matcher.find()){
c = matcher.group(1);
if(c.startsWith("\"") && c.endsWith("\"")){
c = c.substring(1,c.length() - 1);
}
sign = matcher.group(2);
System.out.println("content: '" + c +"'");
if(sign.length() != 0){
System.out.println("sign: '" + sign + "'");
}
content = matcher.group(3);
matcher = pattern.matcher(content);
}
}
}
result:
---------- java ----------
content: 'Robert'
sign: ' - '
content: 'Jones'
sign: ' '
content: ' hello world'
sign: ' + '
content: 'good'
sign: ' '
content: 'hello'Output completed (0 sec consumed) - Normal Termination