简体   繁体   English

需要regex表达式以仅获取python中的TABLE名称和主键

[英]Need regex expression to get only Tably name and primary key in python

May this question is silly, but i am not able to generate the regex expression to fetch table Name and PRIMARY KEY. 可能这个问题很愚蠢,但是我无法生成正则表达式来获取表名和主键。

TABLE: 表:

CREATE TABLE 'dhcpr_dhcprelayinterface'  (
        'vrId' integer default 0,
        'ifName' string ,
        PRIMARY KEY(ifName,vrId),
        FOREIGN KEY (vrId) REFERENCES 'vr_vr'(vrId) ON DELETE CASCADE ON UPDATE CASCADE);

I am using: begin = re.compile(r"CREATE TABLE[ \\"]*([^ \\"]+)[ \\"]*[(]([^/;]+)[/;]",re.IGNORECASE) to fetch all table name and data. 我正在使用: begin = re.compile(r"CREATE TABLE[ \\"]*([^ \\"]+)[ \\"]*[(]([^/;]+)[/;]",re.IGNORECASE)以获取所有表名和数据。

But i would need data only with table name and PRIMARY KEY. 但是我只需要带有表名和PRIMARY KEY的数据。

Expected Output: 预期产量:

dhcpr_dhcprelayinterface
PRIMARY KEY(ifName,vrId)

This solution takes care of some issues you seem not worried about (but which are good to worry about), eg, SQLite allows you to write escaped ' as '' , and there may be any number of spaces, even newlines, between CREATE and TABLE , and between PRIMARY , KEY , and ( : 此解决方案解决了您似乎不担心(但值得担心)的一些问题,例如,SQLite允许您将转义的'编写为'' ,并且CREATECREATE之间可以有任意数量的空格,甚至是换行符。 TABLE以及PRIMARYKEY( :之间

s = """\
CREATE TABLE 'dhcpr_dhcprelayinterface'  (
    'vrId' integer default 0,
    'ifName' string ,
    PRIMARY KEY(ifName,vrId),
    FOREIGN KEY (vrId) REFERENCES 'vr_vr'(vrId)
    ON DELETE CASCADE ON UPDATE CASCADE);
"""

pattern = """
    CREATE \s+ TABLE \s+
    '((?:[^']|'')*)'      # allows escaped single quote
    .+                    # stuff between table name and primary key
    (PRIMARY \s+ KEY\s? \([^)]*\))
"""
mo = re.search(pattern, s, re.IGNORECASE | re.VERBOSE | re.DOTALL)
print(mo.groups())

Output: 输出:

('dhcpr_dhcprelayinterface', 'PRIMARY KEY(ifName,vrId)')

I'm sure you can solve it with regular expressions or sqlparse , but here is a "fun" way of approaching the problem just for educational purposes - using sqlite3 in memory database - actually create the table and get the table_name from the sqlite_master internal table and primary key columns from the PRAGMA table_info : 我敢肯定您可以使用正则表达式或sqlparse来解决它,但这是一种仅出于教育目的解决问题的“有趣”方法- 在内存数据库中使用sqlite3实际创建表并从sqlite_master内部表获取table_namePRAGMA table_info主键列:

import sqlite3

query = """
CREATE TABLE 'dhcpr_dhcprelayinterface'  (
        'vrId' integer default 0,
        'ifName' string ,
        PRIMARY KEY(ifName,vrId),
        FOREIGN KEY (vrId) REFERENCES 'vr_vr'(vrId) ON DELETE CASCADE ON UPDATE CASCADE);
"""

db = sqlite3.connect(":memory:")
cursor = db.cursor()

cursor.execute(query)
db.commit()

# get table name
cursor.execute("select name from sqlite_master where type = 'table'")
table_name = cursor.fetchone()[0]
print(table_name)

# get primary key columns
cursor.execute("PRAGMA table_info(%s);" % table_name)
pk_columns = [row[1] for row in cursor.fetchall()[::-1]]
print(pk_columns)

Prints: 印刷品:

dhcpr_dhcprelayinterface
['ifName', 'vrId']

You can use this to just get the table name and primary key. 您可以使用它来获取表名和主键。

begin = re.compile(r"CREATE TABLE[ ']*([^ ']+)[ ']*[(][^/;]+(PRIMARY KEY.*),[^/;]+;$", re.IGNORECASE)
begin.findall(YOUR_STR)

Outputs: 输出:

In [1]: a = """CREATE TABLE 'dhcpr_dhcprelayinterface'  (
...:         'vrId' integer default 0,
...:         'ifName' string ,
...:         PRIMARY KEY(ifName,vrId),
...:         FOREIGN KEY (vrId) REFERENCES 'vr_vr'(vrId) ON DELETE CASCADE ON
UPDATE CASCADE);"""
In [2]: begin = re.compile(r"CREATE TABLE[ ']*([^ ']+)[ ']*[(][^/;]+(PRIMARY KEY.*),[^/;]+;$", re.IGNORECASE)
In [3]: begin.findall(a)
Out[3]: [('dhcpr_dhcprelayinterface', 'PRIMARY KEY(ifName,vrId)')]

The following was tested using python2.7: 使用python2.7测试了以下内容:

>>> table_string = """
... CREATE TABLE 'dhcpr_dhcprelayinterface'  (
...         'vrId' integer default 0,
...         'ifName' string ,
...         PRIMARY KEY(ifName,vrId),
...         FOREIGN KEY (vrId) REFERENCES 'vr_vr'(vrId) ON DELETE CASCADE ON UPDATE CASCAD
E);"""
>>> p = r'CREATE TABLE\s+\'([^\']+)[\s\S]+PRIMARY KEY\(([^,]+),([^\)]+)\)'
>>> re.findall(p,table_string)
[('dhcpr_dhcprelayinterface', 'ifName', 'vrId')]

The explanation can be found here. 可以在这里找到说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM