使用正则表达式转换手机联系人名单
July 5th, 2009
Categories: 应用
今天换了手机,第一件要紧事就是恢复联系人名单。旧手机是HTC c720W,新手机是Nokia 5320XM,其联系人名单格式不一。难道要我一条条输入吗?阿弥陀佛,几百组联系人的信息,手动操作会死人的。
我看了一下以前备份的HTC c720W联系人名单,(说到这里,表扬一下自己:勤于备份真是好习惯,万一某天灾难降临,你还有个指望),发现其格式是这样的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | <contacts location="0"> <item> <oid>-2147483070</oid> <location>0</location> <businessfaxnumber/> <companyname/> <department/> <email1address/> <mobiletelephonenumber/> <officelocation/> <businesstelephonenumber/> <jobtitle/> <hometelephonenumber/> <email2address/> <email3address/> <home2telephonenumber/> <homefaxnumber/> <categories/> <business2telephonenumber/> <firstname>SomeBody</firstname> <middlename/> <lastname>1355***9214</lastname> <businessaddresspostalcode/> <body/> <pagernumber/> <spouse/> <cartelephonenumber/> <assistantname/> <assistanttelephonenumber/> <children/> <webpage/> <radiotelephonenumber/> <fileas>***</fileas> <title/> <suffix/> <homeaddressstreet/> <homeaddresscity/> <homeaddressstate/> <homeaddresspostalcode/> <homeaddresscountry/> <otheraddressstreet/> <otheraddresscity/> <otheraddressstate/> <otheraddresspostalcode/> <otheraddresscountry/> <businessaddressstreet/> <businessaddresscity/> <businessaddressstate/> <businessaddresscountry/> <anniversary>1899-12-30 00:00:00</anniversary> <birthday>1899-12-30 00:00:00</birthday> </item> <item> ... </item> </contacts> |
而诺基亚的通讯录格式是这样的:
GeSHi Error: GeSHi could not find the language csv (using path /home/zhasm/www/iregex.org/wp-content/plugins/codecolorer/lib/geshi/) (code 2)
本想偷懒,去找个xml2csv什么的,不过不太好用。还是请“正则表达式”这个老朋友帮忙吧!
分析xml文件,发现只有
mobiletelephonenumber,businesstelephonenumber,hometelephonenumber,firstname,lastname这5个字段是有用的;对应的csv字段名称是:
“名”,”姓”,”常用手机”,”常用电话”,”公司电话”
其余的字段大可放心删除。
祭出RegexBuddy,写了这样一条正则表达式:
1 2 3 4 5 6 7 8 9 10 | result = re.sub( r"""(?smx)(?#"名","姓","常用手机","常用电话","公司电话") ^\s*<item>.*? <mobiletelephonenumber/?>(?P<mobile>[^\s<]*).*? <businesstelephonenumber/?>(?P<business>[^\s<]*).*? <hometelephonenumber/?>(?P<home>[^\s<]*).*? <firstname/?>(?P<first>[^\s<]*).*? <lastname/?>(?P<lastname>[^\s<]*).*? </item>""", r'"\g<first>","\g<lastname>","\g<mobile>","\g<home>","\g<business>"', subject) |
之所以使用python格式来写正则,是因为它支持命名捕获,看起人直观一些。其实整个替换过程是在RegexBuddy中进行的。
替换后,保存为CSV文件,使用诺基亚自带的软件导入,几百个联系人就又重新归位了。大爽。

你好,看了你的Regular Expression讲解真的收益良多,
我也下载了一个Regexbuddy,希望以后能一起学习正则表达式,很希望和你聊聊,这是我的qq,290205102,方便的话请加我为好友,
[Reply]
admin Reply:
August 11th, 2009 at 4:38 pm
@只是彼岸花
已加。
@zlf
该问题在http://regex.me/thread-100.html 有回复。
[Reply]
看了你的博客,感觉你对正则很有研究,想请教一个问题:偶数个a和奇数个b的正则怎么写?谢谢~
[Reply]