假设我有一个输入字符串"Tim \"Apple\"" "Mark \"FB\"" "Elon \"Cars\""
我想基于引号(而不是转义引号)将该字符串拆分为String数组 结果应如下所示:
[Tim "Apple", Mark "FB", Elon "cars"]
我应该怎么做才能得到这个结果?非常感谢。
答案 0 :(得分:0)
赞:
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Re {
public static List<String> parse(String s) {
Matcher m = Pattern.compile("\"([^\\\\\"]|\\\\.)+\"") // Match from one quote to the next non-escaped one
.matcher(s);
List<String> matches = new ArrayList<>();
while(m.find()) {
String match = m.group();
match = match.substring(1, match.length() - 1); // Remove the quotes from the beginning and end
match = match.replaceAll("\\\\(.)", "$1"); // Remove all escapes, without accidentally removing escaped backslashes
matches.add(match);
}
return matches;
}
public static void main(String[] args) {
System.out.println(args[0]);
System.out.println(parse(args[0]));
}
}
结果:
"Tim \"Apple\"" "Mark \"FB\"" "Elon \"Cars\""
[Tim "Apple", Mark "FB", Elon "Cars"]