繁体   English   中英

java正则表达式拆分字符串

[英]java regex split string

我有点试图用正则表达式来破解具有以下属性的字符串:

  1. 由|分隔 (管)字符
  2. 如果单个值包含管道,则使用\\(反斜杠)进行转义
  3. 如果单个值以反斜杠结尾,则使用反斜杠进行转义

例如,这里有一些我想要分解的字符串:

  1. One|Two|Three应该屈服: ["One", "Two", "Three"]
  2. One\\|Two\\|Three应该产生: ["One|Two|Three"]
  3. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM