开发者

How to wrap long lines in a text using Regular Expressions when you also need to indent the wrapped lines?

开发者 https://www.devze.com 2023-01-11 12:58 出处:网络
How can one change the following text The quick brown fox jumps over the lazy dog. to The quick brown fox +

How can one change the following text

The quick brown fox jumps over the lazy dog.

to

The quick brown fox +
    jumps over the +
    lazy dog.

using regex?

UPDATE1

A solution for Ruby is still missing... A simple one I came to so far is

def textwrap text, width, indent="\n"
  return text.split("\n").collect do 开发者_开发技巧|line|
    line.scan( /(.{1,#{width}})(\s+|$)/ ).collect{|a|a[0]}.join  indent
  end.join("\n")
end
puts textwrap 'The quick brown fox jumps over the lazy dog.', width=19, indent=" + \n    "
# >> The quick brown fox + 
# >>     jumps over the lazy + 
# >>     dog.


Maybe use textwrap instead of regex:

import textwrap

text='The quick brown fox jumps over the lazy dog.'

print(' + \n'.join(
    textwrap.wrap(text, initial_indent='', subsequent_indent=' '*4, width=20)))

yields:

The quick brown fox + 
    jumps over the + 
    lazy dog.
0

精彩评论

暂无评论...
验证码 换一张
取 消