This question already has an answer here:
I'm splitting a string by three different characters but I want the output to include the characters I split by. Is there any easy way to do this?
This question already has an answer here:
I'm splitting a string by three different characters but I want the output to include the characters I split by. Is there any easy way to do this?
If the split chars were
,
,.
, and;
, I'd try:(?<=PATTERN)
is positive look-behind forPATTERN
. It should match at any place where the preceding text fitsPATTERN
so there should be a match (and a split) after each occurrence of any of the characters.A lot of answers to this! One I knocked up to split by various strings (the original answer caters for just characters i.e. length of 1). This hasn't been fully tested.
Just in case anyone wants this answer aswell...
Instead of
string[] parts = Regex.Split(originalString, @"(?<=[.,;])")
you could usestring[] parts = Regex.Split(originalString, @"(?=yourmatch)")
whereyourmatch
is whatever your separator is.Supposing the original string was
777- cat
777 - dog
777 - mouse
777 - rat
777 - wolf
Regex.Split(originalString, @"(?=777)")
would return777 - cat
777 - dog
and so on
Iterate through the string character by character (which is what regex does anyway. When you find a splitter, then spin off a substring.
pseudo code
That's sort of C# but not really. Obviously, choose the appropriate function names. Also, I think there might be an off-by-1 error in there.
But that will do what you're asking.
Building off from BFree's answer, I had the same goal, but I wanted to split on an array of characters similar to the original Split method, and I also have multiple splits per string: