Split large text string into variable length strings without breaking words and keeping linebreaks and spaces

后端 未结 2 524
不思量自难忘°
不思量自难忘° 2020-12-21 14:38

I am trying to break a large string of text into several smaller strings of text and define each smaller text strings max length to be different. for example:



        
2条回答
  •  余生分开走
    2020-12-21 14:54

    \A(.{0,5}\b)(.{0,11}\b)(.{0,20}\b)+\Z
    

    will capture up to five characters in group 1, up to 11 in group 2 and chunks of up to 20 in group 3. Matches will be split along word delimiters in order to avoid splitting in the middle of a word. Whitespace, line break etc. count as characters and will be preserved.

    The trick is to get at the individual matches in the repeated group, something that can only be done in .NET and Perl 6:

    Match matchResults = null;
    Regex paragraphs = new Regex(@"\A(.{0,5}\b)(.{0,11}\b)(.{0,20}\b)+\Z", RegexOptions.Singleline);
    matchResults = paragraphs.Match(subjectString);
    if (matchResults.Success) {
        String line1 = matchResults.Groups[1].Value;
        String line2 = matchResults.Groups[2].Value;
        Capture line3andup = matchResults.Groups[3].Captures;
        // you now need to iterate over line3andup, extracting the lines.
    } else {
        // Match attempt failed
    } 
    

    I don't know C# at all and have tried to construct this from RegexBuddy's templates and the VB code here, so please feel free to point out my coding errors.

    Note that the whitespace at the beginning of line two is captured at the end of the previous match.

提交回复
热议问题