How can I use a regex find/replace to wrap to new lines so I'll never have more than 20 symbols per line?
I found this:
Find: \s(?<=.{20})
Replace: $0\r\n
It would be perfect, but it leaves words in line bigger than 20 symbols if they started before 20 symbols.
I need a similar expression, but if the last item makes the line bigger it should also go to the new line, so the final line would have always have <20 symbols.
I know I have done it before long ago, perhaps with some plugin, but I can't make it work now. How can I do this?
How can I use a regex find/replace to wrap to new lines so I'll never have more than 20 symbols per line?
I found this:
Find: \s(?<=.{20})
Replace: $0\r\n
It would be perfect, but it leaves words in line bigger than 20 symbols if they started before 20 symbols.
I need a similar expression, but if the last item makes the line bigger it should also go to the new line, so the final line would have always have <20 symbols.
I know I have done it before long ago, perhaps with some plugin, but I can't make it work now. How can I do this?
Share edited Mar 7 at 18:19 Joel Coehoorn 417k114 gold badges578 silver badges815 bronze badges asked Mar 7 at 18:15 Jo MakeinJo Makein 691 silver badge3 bronze badges 3 |1 Answer
Reset to default 3For word wrap it's kind of subjective where to put the line breaks.
For N characters, single pass regex it might be :
(?:
(?:
(?>
( .{1,N} ) # (1)
(?: # break types:
$ # EOS
| (?<= [^\S\r\n] ) # 1. - Behind a non-linebreak whitespace
[^\S\r\n]? # ( optionally accept an extra non-linebreak whitespace )
| (?<= [!,./:;?] ) # 2. - Behind sepcial punctuation breaks
[^\S\r\n]? # ( optionally accept an extra non-linebreak whitespace )
| (?= # 3. - Ahead a linebreak or special punctuation breaks
\r? \n
| [#%&*\-@_]
)
| [^\S\r\n] # 4. - Accept an extra non-linebreak whitespace
)
)
| ( .{1,N} ) # (2)
)
(?: \r? \n )?
| (?: \r? \n )
)
(?:(?:(?>(.{1,N})(?:$|(?<=[^\S\r\n])[^\S\r\n]?|(?<=[!,./:;?])[^\S\r\n]?|(?=\r?\n|[#%&*\-@_])|[^\S\r\n]))|(.{1,N}))(?:\r?\n)?|(?:\r?\n))
Replace $1$2\r\n
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744913871a4600714.html
$1
in the replacement, or match 20 characters and use\K
and replace with a newline – The fourth bird Commented Mar 7 at 18:25(.{1,20})(?:\h|$\R?)
with$1\n
(regex101 demo) – bobble bubble Commented Mar 8 at 13:57