---
title: "一个字符串处理实例"
author: "rokuan"
date: "2011-05-22T08:05:08Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2011-05-22T08:06:27Z"
id: 1054151
url: "https://rokuan.iteye.com/blog/1054151"
---

这个示例实现的功能：
将文本中类似于‘21-12-2011’这样的日期类型找出来，替换为‘2011-12-21’
上代码：

```python
import re
pat = '\d{1,2}-\d{1,2}-\d{4}'
p = re.compile(pat)
f = open('c:/oreacle++emp.txt')
t = f.readline()
while t != '':
    res = re.findall(pat,t)
    if res:
        arr = res[0].split('-')
        arr.reverse()
        print p.subn('-'.join(arr),t)[0],
    else:
        print t,
    t = f.readline()
f.close()
```