1. 程式人生 > >python正則匹配目錄、檔名

python正則匹配目錄、檔名

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# vim:set shiftwidth=2 tabstop=2 expandtab textwidth=79:

import re

filename = "/Users/frankyu/Develop/sso/socialbase/login/dcorators.py"
inputstr = 'Uup'

inputstr = re.escape(inputstr)
m = re.search('.*' + inputstr + '.*', filename) # 普通匹配
if not m:
  pattern = '.*'
  for i in range(len(inputstr)):
    pattern += re.escape(inputstr[i]) + '.*' # 單個字元匹配
  m = re.search(pattern, filename)
  if not m:
    inputstr = inputstr.replace(' ', '') # 去空格後,單個字元匹配
    pattern = '.*'
    for i in range(len(inputstr)):
      pattern += inputstr[i] + '.*'
    m = re.search(pattern, filename)
    if not m:
      print 'can not find it'
    else:
      print m.group(0)
  else:
    print m.group(0)
else:
  print m.group(0)