python 正则表达式

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/12/27 9:52
# @Author  : gylhaut
# @Site    : "http://www.cnblogs.com/gylhaut/"
# @File    : generate_table_struct.py
# @Software: PyCharm

import re


"""
建立相关表的字段
从源表创建指定的MySQL建表脚本

"""
with open('sql_server_table_struct', encoding='UTF-8') as f:
    for line in f.readlines():
      #print(line)
      if line=='\n':
          continue

      if re.match('.*(NOT.*NULL).*', line) is None:
          if re.match('.*(.*NULL.*).*',line) is not None:
            line = line.replace("NULL", " NOT NULL ")

      #print(line)
      # 获取注释
      str_comment='未知'
      list_field=re.findall(r'(\[.*\])',line)
      str_filed = list_field[0].strip()
      #print(str_filed)
      new_field = re.findall(r'\[(.*)\]',str_filed)
      new_field = new_field[0].strip()
      mew_string =re.sub(r'[A-Z]',lambda x:"_"+x.group(0),new_field)
      mew_string =mew_string.lower()
      mew_string = re.findall(r'([a-z]+.*)', mew_string)[0].strip()
      #剩余字符串
      end_field = re.sub(r'(\[.*\])','', line).strip()
      print(str_filed+ ' '+ mew_string + " "+end_field)

  

posted @ 2018-12-27 10:54  流星小子  阅读(171)  评论(0编辑  收藏  举报