比如:C:\\\\abc\\\bcd 或者C:///abc//bcd 格式化为C:\abc\bcd,我的代码如下:
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class FormatPath { private static Pattern pattern; private static Matcher matcher; public static String formatPath(String input) {
pattern = Pattern.compile("(/|\\){2,}");
matcher = pattern.matcher(input);
String out = matcher.replaceAll("\\");
return out;
} public static void main(String args[]) {
String path = "c:\\\\d";
String opath = formatPath(path);
System.out.println(opath); }}
报错Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed group near index 9
(/|\){2,}
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class FormatPath { private static Pattern pattern; private static Matcher matcher; public static String formatPath(String input) {
pattern = Pattern.compile("(/|\\){2,}");
matcher = pattern.matcher(input);
String out = matcher.replaceAll("\\");
return out;
} public static void main(String args[]) {
String path = "c:\\\\d";
String opath = formatPath(path);
System.out.println(opath); }}
报错Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed group near index 9
(/|\){2,}
public class FormatPath { public static String formatPath(String input) {
// 将一个或多个“\”转化成“/”
input = input.replaceAll("\\\\{1,}", "/");
// 将多个“/”转化成一个“/”
input = input.replaceAll("\\/{2,}", "/");
return input;
} public static void main(String args[]) {
String path = "c:\\\\d//f";
String opath = formatPath(path);
System.out.println(opath); }}
首先问个问题 你上面给的路径合法吗?
不合法的是不是应该报错?