How to write replace string for object which will be substituted? [regexp]
MRAB
python at mrabarnett.plus.com
Tue Aug 4 18:55:36 EDT 2009
ryniek90 wrote:
> Hi.
> I started learning regexp, and some things goes well, but most of them
> still not.
>
> I've got problem with some regexp. Better post code here:
>
> "
> >>> import re
> >>> mail = '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$]
> mail [$dot$] com\n'
> >>> mail
> '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$]
> com\n'
> >>> print mail
>
> name at mail.com
> name1 [at] mail [dot] com
> name2 [$at$] mail [$dot$] com
>
> >>> maail = re.sub('^\n|$\n', '', mail)
> >>> print maail
> name at mail.com
> name1 [at] mail [dot] com
> name2 [$at$] mail [$dot$] com
> >>> maail = re.sub(' ', '', maail)
> >>> print maail
> name at mail.com
> name1[at]mail[dot]com
> name2[$at$]mail[$dot$]com
> >>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail)
> >>> print maail
> name at mail.com
> name1 at mail[dot]com
> name2 at mail[$dot$]com
> >>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail)
> >>> print maail
> name at mail.com
> name1 at mail.com
> name2 at mail.com
> >>> #How must i write the replace string to replace all this regexp's
> with just ONE command, in string 'mail' ?
> >>> maail = re.sub('^\n|$\n| |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]',
> *?*, mail)
> "
>
> How must i write that replace pattern (look at question mark), to maek
> that substituion work? I didn't saw anything helpful while reading Re
> doc and HowTo (from Python Doc). I tried with 'MatchObject.group()' but
> something gone wrong - didn't wrote it right.
> Is there more user friendly HowTo for Python Re, than this?
>
> I'm new to programming an regexp, sorry for inconvenience.
>
I don't think you can do it in one regex, nor would I want to. Just use
the string's replace() method.
>>> mail = '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$]
mail [$dot$] com\n'
>>> mail
'\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$]
com\n'
>>> print mail
name at mail.com
name1 [at] mail [dot] com
name2 [$at$] mail [$dot$] com
>>> maail = mail.strip()
name at mail.com
name1 [at] mail [dot] com
name2 [$at$] mail [$dot$] com
>>> maail = maail.replace(' ', '')
>>> print maail
name at mail.com
name1[at]mail[dot]com
name2[$at$]mail[$dot$]com
>>> maail = maail.replace('[at]', '@').replace('[$at$]', '@')
>>> print maail
name at mail.com
name1 at mail[dot]com
name2 at mail[$dot$]com
>>> maail = maail.replace('[dot]', '.').replace('[$dot$]', '.')
>>> print maail
name at mail.com
name1 at mail.com
name2 at mail.com
More information about the Python-list
mailing list