用逗号分隔字符串,但避免使用转义逗号和反斜杠
我想在逗号","
分割一个字符串。 该字符串包含转义的逗号"\,"
并转义反斜杠"\\"
。 开头和结尾的逗号以及连续的几个逗号应该导致空字符串。
所以",,\,\\,,"
应该变成""
, ""
, "\,\\"
, ""
, ""
请注意,我的示例字符串将反斜杠显示为单个"\"
。 Java字符串会使它们加倍。
我尝试了几个包但没有成功。 我的最后一个想法是编写自己的解析器。
在这种情况下,自定义function对我来说听起来更好。 尝试这个:
public String[] splitEscapedString(String s) { //Character that won't appear in the string. //If you are reading lines, '\n' should work fine since it will never appear. String c = "\n"; StringBuilder sb = new StringBuilder(); for(int i = 0;i
不要使用.split()
但要查找(未转义)逗号之间的所有匹配项:
List matchList = new ArrayList (); Pattern regex = Pattern.compile( "(?: # Start of group\n" + " \\\\. # Match either an escaped character\n" + "| # or\n" + " [^\\\\,]++ # Match one or more characters except comma/backslash\n" + ")* # Do this any number of times", Pattern.COMMENTS); Matcher regexMatcher = regex.matcher(subjectString); while (regexMatcher.find()) { matchList.add(regexMatcher.group()); }
结果: ["", "", "\\,\\\\", "", ""]
我使用了占有量词 ( ++
)以避免由嵌套量词引起的过度回溯。
虽然一个专用的库肯定是一个好主意,但以下方法仍然有效
public static String[] splitValues(final String input) { final ArrayList result = new ArrayList (); // (?:\\\\)* matches any number of \-pairs // (?
想法是找到,
前缀为no或偶数编号\
(即没有转义),因为,
是在end()-1
之前切割的模式的最后一部分,就在之前,
。
除了null
-input之外,我可以考虑对大多数赔率进行测试。 如果你更喜欢处理List
你当然可以改变回报; 我刚刚采用了split()
实现的模式来处理转义。
uitilizing此函数的示例类:
import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Print { public static void main(final String[] args) { String input = ",,\\,\\\\,,"; final String[] strings = splitValues(input); System.out.print("\""+input+"\" => "); printQuoted(strings); } public static String[] splitValues(final String input) { final ArrayList result = new ArrayList (); // (?:\\\\)* matches any number of \-pairs // (? 0) { System.out.print("[\""); System.out.print(strings[0]); for(int i = 1; i < strings.length; i++) { System.out.print("\", \""); System.out.print(strings[i]); } System.out.println("\"]"); } else { System.out.println("[]"); } } }