Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string on un-escaped character in D

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?

like image 266
weltensturm Avatar asked Mar 10 '15 14:03

weltensturm


People also ask

How do you split a string at a certain character?

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.

How do you split special characters?

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.

How do you split the last character of a string?

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.


1 Answers

Use a negative lookbehind:

(?<!\\)\!

like image 82
Wiktor Stribiżew Avatar answered Sep 30 '22 01:09

Wiktor Stribiżew