I am looking for a way to split a String in two parts on the forst occurrence of a certain separator. I know this is easy to do when the String looks like this:
String s = "prefix.key value";
String[] a = s.split("[ :=]",2);
But by convention the string may contain escaped separators (with ‘\’ directly in front of the separator). So i updated the regex-String:
String s = "prefix\ key value";
String[] a = s.split("[^\\\\][ :=]",2);
This splits the String at almost the right place, but it cuts off the ‘y’ of key. This is because now the regex matches both the separator an the character in front of it. The split() method cuts out the matched part and only returns the remaining Strings.
I have a working solution that uses split() and looks through the ending characters of the Strings in the returned array, but this seems like an overly complicated and slow way to do it.
Does anyone have a better idea?
Use a negative lookbehind assertion
So your character class will only match if it not preceded by a
\