什么是使用正则表达式来隔离数据的最佳方法

时间:2017-10-17 04:28:19

标签: python regex

我正在尝试编写一个过滤掉跨环境访问的程序,例如。 prod不应该访问Dev / QA对象,反之亦然。

到目前为止,我使用IN条件来检查并过滤掉这些数据,如何使用正则表达式或其他有效方法实现此目的?请建议

示例代码:

lst_role_objects = []
for row in exct_role_obj:
if (('_PROD' in row[0] or  'PROD_'  in row[0] or '_PROD_'  in row[0]) and  ('PREPROD' not in row[0])):

    if ('_DEV' in (row[1].split('.')[0]) or  'DEV_'  in (row[1].split('.')[0]) or '_DEV_'  in (row[1].split('.')[0]) or '_QA' in (row[1].split('.')[0]) or  'QA_'  in (row[1].split('.')[0]) or '_QA_'  in (row[1].split('.')[0])         or '_PREPROD' in (row[1].split('.')[0]) or  'PREPROD_'  in (row[1].split('.')[0]) or '_PREPROD_'  in (row[1].split('.')[0])):


        print(row[0])
        print(row[1].split('.')[0])
        lst_role_objects.append((row[0],row[1]))


for row in exct_role_obj:
if ('_PREPROD' in row[0] or  'PREPROD_'  in row[0] or '_PREPROD_'  in row[0]) or 'QA'  in row[0]:

    if (( 'PREPROD' not in (row[1].split('.')[0]) ) and ( 'QA' not  in (row[1].split('.')[0]))):
        print(row[0])
        print(row[1].split('.')[0])
        lst_role_objects.append((row[0],row[1]))

for row in exct_role_obj:
if ('_DEV' in row[0] or  'DEV_'  in row[0] or '_DEV_'  in row[0] or              'DEV'  in row[0]) :

    if ( 'DEV' not in (row[1].split('.')[0]) ):
        print(row[0])
        print(row[1].split('.')[0])
        lst_role_objects.append((row[0],row[1]))




Sample data :
ROLE , OBJECTS
PROD_A_TEST , DA_DEV.PROD.SLS
PROD_A_TEST , DA_PROD.PROD.SLS
PROD_A_TEST , DA_PREPROD.PREPROD.SLS
PREPROD_A_TEST , DA_PREPROD.PREPROD.SLS
TEST_PREPROD_A , DA_PREPROD.PREPROD.SLS
TEST_PREPROD_A , DA_PROD.PREPROD.SLS

1 个答案:

答案 0 :(得分:0)

这适用于您在此处提及的所有案例。未经适当测试。

lst_role_objects = []
for row in exct_role_obj:
    if re.match("^([A-Z_]*_)?PROD(_[A-Z_]*)?$", row[0]) and re.match("^([A-Z_]*_)?(DEV|QA|PREPROD)(_[A-Z_]*)?\..*", row[1]):
        print row[0], row[1].split('.')[0]
        lst_role_objects.append((row[0], row[1]))

for row in exct_role_obj:
    if re.match("^([A-Z_]*_)?(PREPROD|QA)(_[A-Z_]*)?$", row[0]) and re.match("^((?!([A-Z_]*)(PREPROD|QA))([A-Z_]*)\..*)$", row[1]):
        print row[0], row[1].split('.')[0]
        lst_role_objects.append((row[0], row[1]))

for row in exct_role_obj:
    if re.match("^([A-Z_]*_)?DEV(_[A-Z_]*)?$", row[0]) and re.match("^(?!.*(DEV)).*$", row[1]):
        print row[0], row[1].split('.')[0]
        lst_role_objects.append((row[0], row[1]))

自己尝试将缺少的测试用例包括在内。