当您还需要缩进换行的行时,如何使用正则表达式在文本中换行? [英] How to wrap long lines in a text using Regular Expressions when you also need to indent the wrapped lines?

查看:38
本文介绍了当您还需要缩进换行的行时,如何使用正则表达式在文本中换行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何修改下面的文字

The quick brown fox jumps over the lazy dog.

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

使用正则表达式?

仍然缺少针对 Ruby 的解决方案...到目前为止,我遇到的一个简单解决方案是

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.

推荐答案

也许可以使用 textwrap 而不是正则表达式:

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)))

产量:

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

这篇关于当您还需要缩进换行的行时,如何使用正则表达式在文本中换行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆