Cut the string to be <= 80 characters AND must keep the words without cutting them

前端 未结 4 1638
春和景丽
春和景丽 2021-01-24 07:22

I am new to C#, but I have a requirement to cut the strings to be <= 80 characters AND they must keep the words integrity (without cutting them)

Examples

4条回答
  •  既然无缘
    2021-01-24 07:53

    Try

    ^(.{0,80})(?: |$)
    

    This is a capturing greedy match which must be followed by a space or end of string. You could also use a zero-width lookahead assertion, as in

    ^.{0,80}(?= |$)
    

    If you use a live test tool like http://regexhero.net/tester/ it's pretty cool, you can actually see it jump back to the word boundary as you type beyond 80 characters.

    And here's one which will simply truncate at the 80th character if there are no word boundaries (spaces) to be found:

    ^(.{1,80}(?: |$)|.{80})
    

提交回复
热议问题