regex - Search text in string python -


i have following string

aaa\bbb\ccc\ddd **16 april**\xyz 

the date, in case 16 april, changes depending on start time of event, format of rest of string may change becoming either shorter or longer (below)

aaa\bbb\ccc\ddd\**eee** **16 april**\xyz 

i able select '16 april' regardless of rest of length of rest of variable. date not '16 april' start date of whatever event i'm being fed external program.

i guess

if april in 'aaa\bbb\ccc\ddd\**eee** **16 april**\xyz':     print 'success' 

but didn't know if there better way...

i need can reformat date 16-04-2013..

this should it.

import datetime import re  # note \\x escape \x foo = "aaa\bbb\ccc\ddd **16 april**\\xyz" bar = "aaa\bbb\ccc\ddd\**eee** **1 december**\\xyz"  # \d+ , \w+ aswell, doesn't seem matter in situation pattern = '\*\*(\d{1,2} \w{4,9})\*\*'  # "16 april" etc foo_format = re.search(pattern, foo).group(1) bar_format = re.search(pattern, bar).group(1)  year = str(datetime.datetime.now().year)  # datetime object foo_date = datetime.datetime.strptime(year + " " + foo_format, "%y %d %b") bar_date = datetime.datetime.strptime(year + " " + bar_format, "%y %d %b")  print foo_date.strftime("%y-%m-%d") print bar_date.strftime("%y-%m-%d") 

read more \x in why '\x' invalid in python?


Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -