我在试图编写正则表达式来分解具有以下特性的字符串时遇到了问题:
- 由 |(管道)字符分隔
- 如果单个值包含管道,则使用 \(反斜杠)进行转义
- 如果单个值以反斜杠结尾,则使用反斜杠进行转义
例如,以下是我想要分解的一些字符串:
One|Two|Three
应返回:["One", "Two", "Three"]
One\|Two\|Three
应返回:["One|Two|Three"]
One\\|Two\|Three
应返回:["One\", "Two|Three"]
那么如何使用单个正则表达式拆分它?
更新:正如许多人已经建议的那样,这不是正则表达式的好应用程序。此外,正则表达式解决方案比仅迭代字符慢几个数量级。我最终使用字符迭代。
public static List<String> splitValues(String val) {
final List<String> list = new ArrayList<String>();
boolean esc = false;
final StringBuilder sb = new StringBuilder(1024);
final CharacterIterator it = new StringCharacterIterator(val);
for(char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
if(esc) {
sb.append(c);
esc = false;
} else if(c == '\\') {
esc = true;
} else if(c == '|') {
list.add(sb.toString());
sb.delete(0, sb.length());
} else {
sb.append(c);
}
}
if(sb.length() > 0) {
list.add(sb.toString());
}
return list;
}