Matt wrote:
> I am attempting to reformat a string, inserting newlines before certain
> phrases. For example, in formatting SQL, I want to start a new line at
> each JOIN condition. Noting that strings are immutable, I thought it
> best to spllit the string at the key points, then join with '\n'.
>> Regexps can seem the best way to identify the points in the string
> ('LEFT.*JOIN' to cover 'LEFT OUTER JOIN' and 'LEFT JOIN'), since I need
> to identify multiple locationg in the string. However, the re.split
> method returns the list without the split phrases, and re.findall does
> not seem useful for this operation.
>> Suggestions?
I think that re.sub is a more appropriate method rather than split and
join
trivial example (non SQL):
>>> addnlre = re.compile('LEFT\s.*?\s*JOIN|RIGHT\s.*?\s*JOIN', re.DOTALL + re.IGNORECASE).sub
>>> addnlre(lambda x: x.group() + '\n', '... LEFT JOIN x RIGHT OUTER join y')
'... LEFT JOIN\n x RIGHT OUTER join\n y'