How to insert string in each match using RegEx iterator

504crank at gmail.com 504crank at gmail.com
Wed Jun 10 00:52:36 EDT 2009


On Jun 9, 11:35 pm, "504cr... at gmail.com" <504cr... at gmail.com> wrote:
> On Jun 9, 11:19 pm, Roy Smith <r... at panix.com> wrote:
>
>
>
> > In article
> > <cb258e51-8c54-4b33-9b88-f23fc70a3... at z14g2000yqa.googlegroups.com>,
>
> >  "504cr... at gmail.com" <504cr... at gmail.com> wrote:
> > > By what method would a string be inserted at each instance of a RegEx
> > > match?
>
> > > For example:
>
> > > string = '123 abc 456 def 789 ghi'
> > > newstring = ' INSERT 123 abc INSERT 456 def INSERT 789 ghi'
>
> > If you want to do what I think you are saying, you should be looking at the
> > join() string method.  I'm thinking something along the lines of:
>
> > groups = match_object.groups()
> > newstring = " INSERT ".join(groups)
>
> Fast answer, Roy. Thanks. That would be a graceful solution if it
> works. I'll give it a try and post a solution.
>
> Meanwhile, I know there's a logical problem with the way I was
> concatenating strings in the iterator loop.
>
> Here's a single instance example of what I'm trying to do:
>
> >>> string = 'abc 123 def 456 ghi 789'
> >>> match = rePatt.search(string)
> >>> print string[0:match.start()] + 'INSERT ' + string[match.end():len(string)]
>
> abc INSERT def 456 ghi 789

Thanks Roy. A little closer to a solution. I'm still processing how to
step forward, but this is a good start:

>>> string = 'abc 123 def 456 ghi 789'
>>> rePatt = re.compile('\s\d+\s')
>>> foundGroup = rePatt.findall(string)
>>> newstring = ' INSERT '.join(foundGroup)
>>> print newstring
 123  INSERT  456

What I really want to do is return the full string, not just the
matches -- concatenated around the ' INSERT ' string.



More information about the Python-list mailing list