如何用正则表达式描述一个不在一对小括号中的逗号? 需求是按逗号","来分割字符串,但这个逗号不能包含在一对括号中,比如"(aa,bb) adf , asdfa,afd()"应该返回(aa,bb) adf asdfaafd()这样请教该如何写? 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 这个在java中的正则做不到,因为java的正则不支持平衡组 可以有这个思路 先用正则匹配到括号内的逗号然后修改成任意不常见字符串比如!@#,然后用,split分组,再遍历数组每一项 如果string.contains("!@#")就replace成,关键就是第一步怎么找到括号内的,(?<=\(.*),(?=[^(]*\))可以匹配到这个逗号具体代码:string ss = "(aa,bb) adf , asdfa,afd()"; string newstr = Regex.Replace(ss, @"(?<=\(.*),(?=[^(]*\))", "!@#"); string[] list= newstr.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries); List<string> temp = new List<string>(); foreach (var item in list) { temp.Add(item.Replace("!@#", ",")); } string result = string.Join(",",temp); 好吧,自己写个土办法,先告一段落吧String input= "(aa,bb) adf , asdfa,afd()";List<Integer> l = new ArrayList<Integer>(); int foundCount = 0; byte []arrInput = input.getBytes(); for(int i=0;i<arrInput.length;i++){ if(arrInput[i] == '('){ foundCount++; } if(arrInput[i]==',' && foundCount>0){ l.add(i); } if(arrInput[i]==')'){ foundCount--; } } for(int index : l){ arrInput[index] = '#'; } String res = new String(arrInput); String []cols = res.split(","); 给你个思路,先用正则将所有()中的内容用list存起来,然后就将字符串的相应的内容用A,B,C等等先代替,然后split(","),然后再把A,B,C用list中的对应的换过来 开始匹配括号内的正则我写成这样(?<=\(.*),(?=.*\)) 结果把三个逗号都匹配到了 因为这个字符串最后是以“)”结尾的这个断言匹配到了字符串最后那个“)” 于是改成(?<=\(.*),(?=[^(]*\))让零宽正向先行断言的表达式内不允许出现“(”于是断言只会匹配到“bb)”貌似是贪婪的问题 但是不能使用“?”终止贪婪模式 这样写(?=.*?\))是不对的 取括号中的内容这样不行嘛 regex="\\((.+?)\\)" 请问高手,关于一个基础问题。 用JDBC写的万能查询方法,望大家指点 急!急!急!用java在网页中添加图形的问题 java界面向数据库中插入数据 请帮忙 做了一个个人记帐、网络日记、人际关系管理、团队事务处理的网站,欢迎访问、建议。谢谢! 求Java中字符串扫描程序(400分) 请问javax中有mail包吗? 我用了论坛中一些大虾的sendmail的例子,在编译时出现javax.mail.*不能访问的错误,请问如何解决? 救急:一套关于ATM机的作业,不知道那位大哥能不能帮我一把。 关于继承的问题 正则表达式的使用 问一个关于线程同步的问题在线等
关键就是第一步怎么找到括号内的,
(?<=\(.*),(?=[^(]*\))可以匹配到这个逗号
具体代码:
string ss = "(aa,bb) adf , asdfa,afd()";
string newstr = Regex.Replace(ss, @"(?<=\(.*),(?=[^(]*\))", "!@#");
string[] list= newstr.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries);
List<string> temp = new List<string>();
foreach (var item in list)
{
temp.Add(item.Replace("!@#", ","));
}
string result = string.Join(",",temp);
String input= "(aa,bb) adf , asdfa,afd()";
List<Integer> l = new ArrayList<Integer>();
int foundCount = 0;
byte []arrInput = input.getBytes();
for(int i=0;i<arrInput.length;i++){
if(arrInput[i] == '('){
foundCount++;
}
if(arrInput[i]==',' && foundCount>0){
l.add(i);
}
if(arrInput[i]==')'){
foundCount--;
}
}
for(int index : l){
arrInput[index] = '#';
}
String res = new String(arrInput);
String []cols = res.split(",");
因为这个字符串最后是以“)”结尾的这个断言匹配到了字符串最后那个“)”
于是改成(?<=\(.*),(?=[^(]*\))让零宽正向先行断言的表达式内不允许出现“(”于是断言只会匹配到“bb)”
貌似是贪婪的问题 但是不能使用“?”终止贪婪模式 这样写(?=.*?\))是不对的