Pattern Search Regular Expression

rurpy at yahoo.com rurpy at yahoo.com
Sat Jun 15 12:59:35 EDT 2013


On 06/15/2013 03:42 AM, subhabangalore at gmail.com wrote:> Dear Group,
> 
> I am trying to search the following pattern in Python.
> 
> I have following strings:
> 
>  (i)"In the ocean"
>  (ii)"On the ocean"
>  (iii) "By the ocean"
>  (iv) "In this group"
>  (v) "In this group"
>  (vi) "By the new group"
>        .....
> 
> I want to extract from the first word to the last word, 
> where first word and last word are varying.
> 
> I am looking to extract out:
>   (i) the
>   (ii) the 
>   (iii) the
>   (iv) this
>   (v) this
>   (vi) the new
>       .....
> 
> The problem may be handled by converting the string to list and then 
> index of list. 
> 
> But I am thinking if I can use regular expression in Python.

Since nobody here seems to want to answer your question
(or seems even able to read it), I'll try.  Is something 
like this what you want?

import re

texts = [
    '(i)"In the ocean"',
    '(ii)"On the ocean"',
    '(iii) "By the ocean"',
    '(iv) "In this group"',
    '(v) "In this group"',
    '(vi) "By the new group"']

pattern = re.compile (r'^\((.*)\)\s*"\S+\s*(.*)\s\S+"$')
for txt in texts:
    matchobj = re.search (pattern, txt)
    number, midtext = matchobj.group (1, 2)
    print ("(%s) %s" % (number, midtext))





More information about the Python-list mailing list