import java.util.regex.*; public class Test { public static void main(String[] args) { Pattern p = Pattern.compile("([^,]*),([^,]*),([^,]*)"); String s = "111,123,\"ab12\""; Matcher m = p.matcher(s); m.find(); System.out.println(m.group(1)+","+m.group(3)+","+m.group(2)); }}
没有更优雅的做法吗?利用Matcher的特性的
public class CopyOfCopy_3_of_Test { public static void main(String[] args) { String str = "111,123,\"ab12\""; String regex = "((?<=,)[^,]*?(?=,)),((?<=,)[^,]*?(?=$))"; System.out.println(str); System.out.println(str.replaceAll(regex, "$2,$1")); } } 结果:111,123,"ab12" 111,"ab12",123
import java.util.regex.*;
public class Test {
public static void main(String[] args) {
Pattern p = Pattern.compile("([^,]*),([^,]*),([^,]*)");
String s = "111,123,\"ab12\"";
Matcher m = p.matcher(s);
m.find();
System.out.println(m.group(1)+","+m.group(3)+","+m.group(2));
}}
public class CopyOfCopy_3_of_Test {
public static void main(String[] args) {
String str = "111,123,\"ab12\"";
String regex = "((?<=,)[^,]*?(?=,)),((?<=,)[^,]*?(?=$))";
System.out.println(str);
System.out.println(str.replaceAll(regex, "$2,$1"));
}
}
结果:111,123,"ab12"
111,"ab12",123
public static void main(String[] args) {
String tmp = null;
String str = "111,123,\"ab12\"";
String[] tmpStr = str.split(",");
tmp = tmpStr[1];
tmpStr[1] = tmpStr[2];
tmpStr[2] = tmp;
for(String s : tmpStr){
System.out.println(s);
}
}
第一个组匹配两个,号之间的部分
第二个组匹配,号和行锚点$(一行的结尾)之间的部分
(?<=,)这个的意思是匹配,号之后的位置,不捕获这个,号
(?=,)的意思是匹配,号之间的位置,不捕获这个,号
[^,]*?是匹配非,号的字符,量词*?是非贪婪模式匹配多个的意思((?<=,)[^,]*?(?=,))这个组捕获123
((?<=,)[^,]*?(?=$))这个组捕获"ab12"replaceAll中的第一个参数是正则,第二个是要替换的字符串,$1代表前面正则组1匹配的的内容,$2代表组2匹配的内容
呵呵,都是小知识点
str.replaceAll(regex, "$2,$1")
就可以替换后面的字符串
"$2,$1"就是"ab12",123啊
正则匹配的是123,"ab12"
也就是说吧123,"ab12"替换成"ab12",123这个