What is the best way to split a string on an un-escaped character? Eg. split this (raw) string
`example string\! it is!split in two parts`
on '!', so that it produces this array:
["example string! it is", "split in two parts"]
std.regex.split
seems to almost be the right thing. There is a problem though, this code matches the correct split character, but also consumes the last character on the left part.
auto text = `example string\! it is!split in two parts`;
return text.split(regex(`[^\\]!`)).map!`a.replace("\\!", "!")`.array;
The whole regex match is removed on split, so this array is the result:
["example string! it i", "split in two parts"]
What is the best way to get to the first array without iterating the string myself?
To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.
To split a string by special characters, call the split() method on the string, passing it a regular expression that matches any of the special characters as a parameter. The method will split the string on each occurrence of a special character and return an array containing the results.
To split a string on the last occurrence of a substring:, use the lastIndexOf() method to get the last index of the substring and call the slice() method on the string to get the portions before and after the substring you want to split on.
Use a negative lookbehind:
(?<!\\)\!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With