如何用正则表达式分割字符串

slin 2006-11-10 10:29:07
String a="PartA PartB \"2006-11-13 8:00:00\" \"2006-11-13 9:30:00\" PartC"
请问如果写正则表达式进行分割出下面的数组出来:
PartA
PartB
"2006-11-13 8:00:00"
"2006-11-13 9:30:00"
PartC
也就是说凡是引号里面的空格就不进行分割了。

知道的朋友帮下忙,先谢谢了!

...全文
917 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
healer_kx 2006-11-11
  • 打赏
  • 举报
回复
格式明确的用字符串操作,正则比较慢.
wizardblue 2006-11-11
  • 打赏
  • 举报
回复

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Splitter {
public static void main(String[] args) {
String a="PartA PartB \"2006-11-13 8:00:00\" \"2006-11-13 9:30:00\" PartC";
split(a);

}

private static void split(String s) {

String regex = "[\"]{1}[^\"]*[\"]{1}|[\\S]+";
System.out.println(regex);
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher( s);
while(m.find()){
String ss = m.group();
System.out.println(ss);
}
}

}
wizardblue 2006-11-11
  • 打赏
  • 举报
回复


import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



public class Splitter {
public static void main(String[] args) {
String a="PartA PartB \"2006-11-13 8:00:00\" \"2006-11-13 9:30:00\" PartC";
split(a);
//T.show(splitV2(a));
}

private static void split(String s) {

String regex = "[\"]{1}[^\"]*[\"]{1}|[\\S]+";
System.out.println(regex);
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher( s);
while(m.find()){
String ss = m.group();
System.out.println(ss);
}
}
private static String[] splitV2(String s){
List resList = new ArrayList();
int posIndex = 0;
int[] pos = new int[2];
String temp = "";
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
if(c==' '&&posIndex ==0){
if(!temp.equals("")){
resList.add(temp);
temp="";
}
continue;
}
if(c=='"'){
temp+=c;
pos[posIndex++]=i;
if(posIndex==2){
posIndex = 0;
resList.add(temp);
temp="";
}
continue;
}
temp+=c;
}
resList.add(temp);

return (String[])resList.toArray(new String[0]);
}

}
andycpp 2006-11-11
  • 打赏
  • 举报
回复
mark
mingxuan3000 2006-11-11
  • 打赏
  • 举报
回复
我要解析xml文件,不用java
的api,自己写一个,是不是用正则?
如:
<aa>
<bb>111
</bb>
</aa>

要取得getElementByTagName("bb"),是不是用正则匹配<bb></bb>中的内容,这个该怎么写?

要取得getElementByTagName("aa"),用正则匹配<aa></aa>中的内容
slin 2006-11-10
  • 打赏
  • 举报
回复
在线等待啊。。。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧