Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string by java regex with look behind?

Tags:

java

regex

I read this string from file:

abc | abc (abc\|abc)|def

I want to get array inludes 3 items:

  1. abc
  2. abc (abc\|abc)
  3. def

How to write regex correctly? line.split("(?!<=\\)\\|") doesn't work.

like image 385
mystdeim Avatar asked Oct 31 '22 00:10

mystdeim


1 Answers

Code:

public class __QuickTester {

    public static void main (String [] args) {

        String test = "abc|abc (abc\\|abc)|def|banana\\|apple|orange";

        // \\\\ becomes \\ <-- String
        // \\ becomes \ <-- In Regex
        String[] result = test.split("(?<!\\\\)\\|");

        for(String part : result) {
            System.out.println(part);
        }
    }
}

Output:

abc
abc (abc\|abc)
def
banana\|apple
orange


Note: You need \\\\ (4 backslashes) to get \\ (2 backslashes) as a String, and then \\ (2 backslashes) becomes a single \ in Regex.

like image 92
almightyGOSU Avatar answered Nov 08 '22 06:11

almightyGOSU