[英]java regex split string
我有点试图用正则表达式来破解具有以下属性的字符串:
例如,这里有一些我想要分解的字符串:
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;
}
诀窍是不使用split()
方法。 这会强制您使用lookbehind来检测转义字符,但是当转义本身被转义时(如您所发现的那样),这会失败。 您需要使用find()
来匹配标记而不是分隔符:
public static List<String> splitIt(String source)
{
Pattern p = Pattern.compile("(?:[^|\\\\]|\\\\.)+");
Matcher m = p.matcher(source);
List<String> result = new ArrayList<String>();
while (m.find())
{
result.add(m.group().replaceAll("\\\\(.)", "$1"));
}
return result;
}
public static void main(String[] args) throws Exception
{
String[] test = { "One|Two|Three",
"One\\|Two\\|Three",
"One\\\\|Two\\|Three",
"One\\\\\\|Two" };
for (String s :test)
{
System.out.printf("%n%s%n%s%n", s, splitIt(s));
}
}
输出:
One|Two|Three
[One, Two, Three]
One\|Two\|Three
[One|Two|Three]
One\\|Two\|Three
[One\, Two|Three]
One\\\|Two
[One\|Two]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.