我想使用子函數來格式化字符串 「Ross McFluff:0456-45324:155 Elm Street \ nRonald Heathmore:5543-23464:445 Finley Avenue」。更多正則表達式解決方案?
每個人就應該是這樣的:
Contact
Name: xx yy
Phone number: 0000-00000
Address: 000 zzz zzz
我試圖解決這個問題:
line = """Ross McFluff: 0456-45324: 155 Elm Street \nRonald Heathmore: 5543-23464: 445 Finley Avenue"""
match = re.sub(r':', r'', line)
rematch = re.sub(r'([A-Z][a-z]+\s[A-Z][a-zA-Z]+)(.*?)(\d\d\d\d-\d\d\d\d\d)', r'Contact. Name: \1. Phone number: \3. Address:\2', match)
我得到了這樣的事情:
"Contact. Name: Ross McFluff. Phone number: 0456-45324. Address: 155 Elm Street \nContact. Name: Ronald Heathmore. Phone number: 5543-23464. Address: 445 Finley Avenue"
哪有我做得到這個結果:
Contact
Name: Ross McFluff
Phone number: 0456-45324
Address: 155 Elm Street
Contact
Name: Ronald Heathmore
Phone number: 5543-23464
Address: 445 Finley Avenue
有什麼想法?感謝 /喬治
您不必使用正則表達式,它是一個非常簡單的csv。你可以一行一行讀取字符串,並用':'分割它。 –
我知道,但是我想用正則表達式來解決這個問題;) –