String Range forward and backward lookaround

拈花ヽ惹草 提交于 2019-12-04 19:27:59

The string range operation is pretty stupid; it doesn't know anything about the string it is splitting other than that it contains characters. To get smarter splitting, your best bet is probably an intelligently chosen regular expression:

set s "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod\
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis\
nostrud exercitation ullamco laboris."

# Up to 40 characters, from word-start, to word-start or end-of-string
set RE {\m.{1,40}(?:\m|\Z)}
# Extract the split-up list of "lines" and print them as lines
puts [join [regexp -all -inline $RE $s] "\n"]

This produces this output for me:

Lorem ipsum dolor sit amet, consectetur 
adipisicing elit, sed do eiusmod tempor 
incididunt ut labore et dolore magna 
aliqua. Ut enim ad minim veniam, quis 
nostrud exercitation ullamco laboris.

Implementing full justification by inserting spaces is left as an exercise for the reader (because it's really quite a lot harder than greedy line splitting!)

glenn jackman

The textutil::adjust module in tcllib is what you need:

package require textutil::adjust
set line "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris"
set formatted [textutil::adjust::adjust $line -length 41]
puts $formatted
Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!