我想使用regex替换除java中的双引号之外的所有逗号。我将输出除外\"Lee Rounded Neck, Printed\"#410.00#300.00#\"Red Blue\"#lee"
String line="\"Lee Rounded Neck, Printed\" 410.00 300.00,\"Red Blue\",lee";
String repl = line.replaceAll("(?!\")\\,", "#");
System.out.println("Replaced => " + repl);
但我得到了"Lee Rounded Neck# Printed" 410.00 300.00#"Red Blue"#lee
请有人在这方面帮助我
答案 0 :(得分:2)
试试,
line.replaceAll(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", "#");
答案 1 :(得分:1)
没有正则表达式:
String line="\"Lee Rounded Neck, Printed\" 410.00 300.00,\"Red Blue\",lee";
System.out.println(line);
char[] line2 = line.toCharArray();
boolean insideQuotes = false;
for (int i = 0; i < line.length(); ++i) {
if (line.charAt(i) == '\"')
insideQuotes = !insideQuotes;
else if (line.charAt(i) == ',' && !insideQuotes)
line2[i] = '#';
}
line = String.valueOf(line2);
System.out.println(line);
输出:
"Lee Rounded Neck, Printed" 410.00 300.00,"Red Blue",lee
"Lee Rounded Neck, Printed" 410.00 300.00#"Red Blue"#lee