phobos and splitting things... but not with whitespace.

Chad J chadjoan at __spam.is.bad__gmail.com
Sat Jun 23 12:51:26 PDT 2012


On 06/23/2012 03:41 PM, simendsjo wrote:
> On Sat, 23 Jun 2012 20:41:29 +0200, Chad J
> <chadjoan at __spam.is.bad__gmail.com> wrote:
>
>> IMO the "take away a single line" thing should be accomplishable with
>> a single concise expression
>
> This takes a range to match against, so much like startsWith:
>
> auto findSplitAny(Range, Ranges...)(Range data, Ranges matches) {
> auto rest = data;
> for(; !rest.empty; rest.popFront()) {
> foreach(match; matches) {
> if(rest.startsWith(match)) {
> auto restStart = data.length-rest.length;
> auto pre = data[0..restStart];
> // we'll fetch it from the data instead of using the supplied
> // match to be consistent with findSplit
> auto dataMatch = data[restStart..restStart+match.length];
> auto post = rest[match.length..$];
> return tuple(pre, dataMatch, post);
> }
> }
> }
> return tuple(data, Range.init, Range.init);
> }
> unittest {
> auto text = "1\n2\r\n3\r4";
>
> auto res = text.findSplitAny("\r\n", "\n", "\r");
> assert(res[0] == "1");
> assert(res[1] == "\n");
> assert(res[2] == "2\r\n3\r4");
>
> res = res[2].findSplitAny("\r\n", "\n", "\r");
> assert(res[0] == "2");
> assert(res[1] == "\r\n");
> assert(res[2] == "3\r4");
>
> res = res[2].findSplitAny("\r\n", "\n", "\r");
> assert(res[0] == "3");
> assert(res[1] == "\r");
> assert(res[2] == "4");
>
> res = res[2].findSplitAny("\r\n", "\n", "\r");
> assert(res[0] == "4");
> assert(res[1] == "");
> assert(res[2] == "");
> }

I, for one, would like to see that in phobos...
Although it should probably be called findSplitAmong to be consistent 
with findAmong ;)


More information about the Digitalmars-d-learn mailing list