Regex to split up message_txt over 160 characters <p>I am trying to split message text for a messaging system up into at most 160 character long sequences that end in spaces, unless it is the very last sequence, then it can end in anything as long as it is equal to or less than 160 characters.</p> <p>this re expression '.{1,160}\s' almost works however it cuts of the last word of a message because generally the last character of a message is not a space.</p> <p>I also tried '.{1,160}\s|.{1,160}' but this does not work because the final sequence is just the remaining text after the last space. Does anyone have an idea on how to do this?</p> <p>EXAMPLE:</p> <pre><code>two_cities = ("It was the best of times, it was the worst of times, it was " + "the age of wisdom, it was the age of foolishness, it was the " + "epoch of belief, it was the epoch of incredulity, it was the " + "season of Light, it was the season of Darkness, it was the " + "spring of hope, it was the winter of despair, we had " + "everything before us, we had nothing before us, we were all " + "going direct to Heaven, we were all going direct the other " + "way-- in short, the period was so far like the present period," + " that some of its noisiest authorities insisted on its being " + "received, for good or for evil, in the superlative degree of " + "comparison only.") chunks = re.findall('.{1,160}\s|.{1,160}', two_cities) print(chunks) </code></pre> <p>will return </p> <p>['It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of ', 'incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we ', 'had nothing before us, we were all going direct to Heaven, we were all going direct the other way-- in short, the period was so far like the present period, ', 'that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison ', 'only.']</p> <p>where the final element of the list should be </p> <p>'that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.'</p> <p>not 'only.'</p>