当您还需要缩进换行时,如何使用正则表达式在文本中换行?

发布于 2024-09-14 05:43:29 字数 646 浏览 5 评论 0原文

如何将以下文本更改

The quick brown fox jumps over the lazy dog.

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

使用正则表达式?

UPDATE1

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

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.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏天碎花小短裙 2024-09-21 05:43:29

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

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.

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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文