Extracting parts of string between anchor points
Jignesh Sutar
jsutar at gmail.com
Thu Feb 27 15:07:56 EST 2014
I've kind of got this working but my code is very ugly. I'm sure it's
regular expression I need to achieve this more but not very familiar with
use regex, particularly retaining part of the string that is being
searched/matched for.
Notes and code below to demonstrate what I am trying to achieve. Any help,
much appreciated.
Examples=["Test1A",
"Test2A: Test2B",
"Test3A: Test3B -:- Test3C", ""]
# Out1 is just itself unless if it is empty
# Out2 is everything left of ":" (including ":" i.e. part A) and right of
"-:-" (excluding "-:-" i.e. part C)
# If text doesn't contain "-:-" then return text itself as it is
# Out3 is everything right of "-:-" (excluding "-:-" i.e. part C)
# If text doesn't contain "-:-" but does contains ":" then return part B
only
# If it doesn't contain ":" then return itself (unless if it empty then
"None")
for i,s in enumerate(Examples,start=1):
Out1=s if len(s)>0 else "Empty"
Out2=s[:s.find(":")+3] + s[s.find("-:-")+5:] if s.find("-:-")>0 else
s.strip() if len(s) else "Empty"
Out3=s[s.find("-:-")+4:] if s.find("-:-")>0 else
s[s.find(":")+1:].strip() if s.find(":")>0 and len(s)!=s.find(":")+1 else s
if len(s) else "Empty"
print "Item%(i)s <%(s)s> Out1 = %(Out1)s" % locals()
print "Item%(i)s <%(s)s> Out2 = %(Out2)s" % locals()
print "Item%(i)s <%(s)s> Out3 = %(Out3)s" % locals()
Output:
Item1 <Test1A> Out1 = Test1A
Item1 <Test1A> Out2 = Test1A
Item1 <Test1A> Out3 = Test1A
Item2 <Test2A: Test2B> Out1 = Test2A: Test2B
Item2 <Test2A: Test2B> Out2 = Test2A: Test2B
Item2 <Test2A: Test2B> Out3 = Test2B #INCORRECT - Should be "Test2A:
Test2B"
Item3 <Test3A: Test3B -:- Test3C> Out1 = Test3A: Test3B -:- Test3C
Item3 <Test3A: Test3B -:- Test3C> Out2 = Test3A: Test3C
Item3 <Test3A: Test3B -:- Test3C> Out3 = Test3C
Item4 <> Out1 = Empty
Item4 <> Out2 = Empty
Item4 <> Out3 = Empty
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20140227/22e9b2cd/attachment.html>
More information about the Python-list
mailing list