c# - string.split but keeping sequential matches -
i've sifted through many questions haven't come across 1 answered me.
string input = "~abc~~~123~~~hijkl~9"; string[] postsplit = input.split('~');
the response see is:
[0]-""
[1]-"abc"
[2]-""
[3]-""
[4]-"123"
...
notice there 2 entries between "abc" , "123" though there 3 delimiters.
note: i've tried string.split , regex.split methods same results.
how can go making sure regardless of number of sequential delimiters, array entry each. (3 entries between "abc" , "123")
thanks in advance.
update:
- i understand expected behavior.
- if more information on matter given, more might understand why input should not changed.
- my "expectation" workaround/answer this... going have extension method hand built. wanted see if had solved problem , built wheel.
update2: tilde in scenario represents either delimiter of fields or empty value never placed string. ~a~b delimiter between , b, ~a~~~c represents delimiter, empty value, delimiter c
update3:
~~~ represents a~~~c in array [a][""][c] ~ represents a~b in array [a][b] 1 , multiples of 3 tilde appear between valid inputs
a~~~~~~~~~b should equate [a][""][""][""][b]
note: answer addresses parts of question preceding "update" paragraph, because written before question edited.
string.split
produce n-1 empty parts n consecutive separator characters. since want produce n empty parts instead, 1 tilde short wherever several of them occur consequtively. add "missing" tildes follows before perform split
:
// using system.text.regularexpressions; const string input = "~abc~~~123~~~hijkl~9"; string[] parts = regex.replace(input, "~~+", "$0~").split('~'); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Comments
Post a Comment