有没有一种简单的方法可以将一行文本拆分为一系列较短的行,给定一些最大上限而不拆分单词,除非单词本身长于该上限?
您可以匹配以下正则表达式,该表达式将行长度限制为 40 个字符。每个匹配项都是最大长度的非空行,以非空白字符开头和结尾,包含不超过 40 个字符,并且不会破坏给定字符串中非空白字符的子字符串,除非这样的子字符串包含超过40 个非空白字符,在这种情况下,它在第 40 个字符之后断开。
\S{40}| *\r?\n|\S.{0,38}\S(?!\S)
Run Code Online (Sandbox Code Playgroud)
对于字符串:
All good programmers should take note and come to the aid of their company's bowling team.
Moreover, they should always be mindful that non-words, such as abcdefghiabcdefghiabcdefghiabcdefghiabcdefg may need to be split.
Also, blank lines are to be retained.
Run Code Online (Sandbox Code Playgroud)
比赛如下:
1 2 3
0123456789012345678901234567890123456789
All good programmers should take note
and come to the aid of their company's
bowling team.
Moreover, they should always be mindful
that non-words, such as
abcdefghiabcdefghiabcdefghiabcdefghiabcd
efg may need to be split.
Also, blank lines are to be retained.
Run Code Online (Sandbox Code Playgroud)
正则表达式为:“匹配 40 个非空白字符或匹配零个或多个空格、可选的回车和换行符或匹配非空白字符后跟最多 38 个字符,后跟非空白字符后跟一个非空白字符”。“后面没有非空白字符”表示该字符后面是空白字符或者是行中的最后一个字符。(?!\S)是一个负面的前瞻。
| 归档时间: |
|
| 查看次数: |
96 次 |
| 最近记录: |