我正在try 解析一条SQL语句(存储在一个文件中),并且只保存字段名 因此,对于以下几点:

SELECT
Involved_Party_ID=pt.ProgramId,
Involved_Party_Type=2, 
First_Name=REPLACE(REPLACE(REPLACE(pt.ProgramName, '|', '/'), CHAR(10), ' '), CHAR(13), ' '),
Registration_Status=pt.RegistrationStatus,
Involved_Party_Status=CONVERT(SMALLINT, pt.ProgramStatus), 
Creation_Date=pt.CreationDate,
Incorporation_Country=CONVERT(VARCHAR(50), CASE WHEN pd.IncorporationCountry='UK' THEN 'GB' ELSE pd.IncorporationCountry END),
FROM
    SomeTable AS pt
GO

所需输出将为:

Involved_Party_ID
Involved_Party_Type
First_Name
Registration_Status
Involved_Party_Status
Creation_Date
Incorporation_Country

以下是我的代码:

import re

File1 = open("File1 .sql", "r")
File2 = open("File2 .sql", "w")
    for line in File1:
        if re.match('\s*SELECT\s*', line):
            continue
        if re.match('\s*FROM\s*', line):
            break
        if re.match('(\n).*?(?=(=))', line):
            Field_Name = re.search('(\n).*?(?=(=))', line)
            File2 .write(Field_Name.group(0) + '\n')

我首先try 使用这个正则表达式:

'.*?(?=(=))'

但后来我的结果是:

Involved_Party_ID
Involved_Party_Type
First_Name
Registration_Status
Involved_Party_Status
Creation_Date
Incorporation_Country
CONVERT(VARCHAR(50), CASE WHEN pd.IncorporationCountry

Now that I've added (\n) to my regular expression the file returns completely empty although online regular-expression testing sites return the desired outcome. enter image description here (I'm not concerned about the whitespaces matching the regexp as I'm only retrieving the first result per line)

推荐答案

从您对re.match使用的模式来看,您可以在这里不使用正则表达式.只需跳过以SELECT开头的行,在以FROM开始的行处停止匹配,并收集前=行之间的行的部分:

File1 = open("File1 .sql", "r")
File2 = open("File2 .sql", "w")
for line in File1:
    if line.strip().startswith("SELECT"):
        continue
    elif line.strip().startswith("FROM"):
        break
    else:
        result = line.strip().split("=", 1)[0]
        File2.write(result + '\n')

我得到的输出是

Involved_Party_ID
Involved_Party_Type
First_Name
Registration_Status
Involved_Party_Status
Creation_Date
Incorporation_Country

请参见this Python demo.

Python相关问答推荐

Pandas基于另一列的价值的新列

查找3D数组中沿一个轴的相同值序列的长度(与行程长度编码相关)

PyTorch卷积自动编码器,输出维度与输入不同

Django序列化器没有验证或保存数据

两极:如何分割一个大 pyramid 并并行保存每个

如何在Python中增量更新DF

如何从具有多个嵌入选项卡的网页中Web抓取td类元素

如何才能知道Python中2列表中的巧合.顺序很重要,但当1个失败时,其余的不应该失败或是0巧合

即使在可见的情况下也不相互作用

如何将ctyles.POINTER(ctyles.c_float)转换为int?

加速Python循环

Julia CSV for Python中的等效性Pandas index_col参数

如何在给定的条件下使numpy数组的计算速度最快?

将9个3x3矩阵按特定顺序排列成9x9矩阵

在vscode上使用Python虚拟环境时((env))

在含噪声的3D点网格中识别4连通点模式

Geopandas未返回正确的缓冲区(单位:米)

Polars将相同的自定义函数应用于组中的多个列,

numpy.unique如何消除重复列?

python中csv. Dictreader. fieldname的类型是什么?'