将给定文本中的长行换行到给定长度。例:
'To be or not to be-that is the question', 5 =>
To be
or
not
to be
-that
is
the
quest
ion
答案 0 :(得分:0)
这解决了您的问题:
max_length = 5
result = ""
word_array = 'To be or not to be-that is the question'.split(/\s|-/)
line = word_array.shift
word_array.each do |word|
if (line + " " + word).length <= max_length
line << " " + word
elsif word.length > max_length
result << line + "\n" unless line.empty?
line = ""
word.each_char do |c|
line << c
if line.length == max_length
result << line + "\n"
line = ""
end
end
else
result << line + "\n"
line = word
end
end
result << line
puts result
答案 1 :(得分:0)
这可能会有所帮助
gosu
https://regex101.com/r/E7FxHg/1
# http://stackoverflow.com/questions/20431801/word-wrapping-with-regular-expressions/20434776#20434776
# MS-Windows "Notepad.exe Word Wrap" simulation
# ( N = 16 )
# ------------------
# Trims optional non-linebreak whitespace
# external to the viewport
# ============================
# Find: @"(?:(?:(?>(.{1,16})(?:(?<=[^\S\r\n])[^\S\r\n]?|(?<=[,.;:!/?])|(?=\r?\n|[-#%&*@_])|[^\S\r\n]))|(.{1,16}))(?:\r?\n)?|(?:\r?\n))"
# Replace: @"$1$2\r\n"
# Flags: Global