0

I have a Codefragment that works for every escape except \ the problem i have is that split removes all \

     public static String esc = "\\";
     public static String[] saveSplit(String str, String regex) {
        String[] test = str.split(regex);
        ArrayList<String> list = new ArrayList<>();
        String storage = "";
        for (String string : test) {
            if (!endsWith(string, esc)) {
                if (!storage.equals("")) {
                    list.add(storage + string);
                    storage = "";
                    continue;
                }
                list.add(string);
            } else {
                storage += string.replace(esc, regex);
            }
        }
        if (!storage.equals("")) {
            list.add(storage);
        }
        String[] retArray = new String[list.size()];
        retArray = list.toArray(retArray);
        return retArray;
    }

i need this method to savely split a string that have \ without removing the \ so when i escape the \\ with \\\\ they wont get lost

what i excpect is that String s = "\\\\element1\\element2\\\\\\element3\\\\element4 turns to [{\\element1},{element2},{\\element3\\element4}] but it removes all \

  • 1
    Possible duplicate of [Replacing single '\' with '\\' in Java](https://stackoverflow.com/questions/14183248/replacing-single-with-in-java) – Leviand May 27 '19 at 14:07
  • If you want to split without removing the elements you want to split at, you'll need a look-behind and look-ahead, e.g. a regex like `(?<=[^\\])(?=\\)` (meaning "any non-backslash before the match and a backslash after the match" which means the zero-width position right in between). Thus `"\\\\element1\\element2\\\\\\element3\\\\element4".split("(?<=[^\\\\])(?=\\\\)")` would result in `["\\\\element1", "\\element2", "\\\\\\element3", "\\\\element4"]`. You should then be able to work from there to get your desired output. – Thomas May 27 '19 at 14:27

0 Answers0