簡體   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