Insert characters into string based on re ?

Duncan Booth duncan.booth at invalid.invalid
Fri Oct 13 07:46:52 EDT 2006


harvey.thomas at informa.com wrote:

> 
> 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'. 
> 
> 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'
> 
> 
Quite apart from the original requirement being to insert newlines before 
rather than after the phrase, I wouldn't have said re.sub was appropriate.

>>> addnlre(lambda x: x.group() + '\n',
 "select * from whatever where action in ['user left site', 'user joined site']")
"select * from whatever where action in ['user left site', 'user join\ned site']"

or with the newline before the pattern:

>>> addnlre(lambda x: '\n'+x.group(),
 "select * from whatever where action in ['user left site', 'user joined site']")
"select * from whatever where action in ['user \nleft site', 'user joined site']"




More information about the Python-list mailing list