是否有通用的正则表达式方法可以结合这些条件?

Is there a general regex method can combine those conditions?

在我的代码中,我使用了四个四个正则表达式条件但是它太长了,那么有没有简单或通用的方法可以组合这些条件? 我试过 r'[(abc|def)+^((?!(xyz|efg)).)*$^.*[^,|.]$]{1,10}$' 但没成功...

s_l = ['abcabcabcabc', 'defdef.', 'sssssss', 'def', 'def,', 'xyzabc,', 'efgdefefg']

for idx, str_item in enumerate(s_l):
    if (re.match(r'(abc|def)+', str_item)  # find abc or def in str
    and re.match(r'^((?!(xyz|efg)).)*$', str_item)  # find xyz and efg not in str 
    and re.match(r'^.*[^,|.]$', str_item)   # comma not in the end of str
    and re.match(r'^[a-zA-Z]{1,10}$', str_item)):  # find length of str smaller than 10
        print(idx, "True")
    else:
        print(idx, "False")

您可以大大简化条件表达式。

regexes = (r'(abc|def)+', r'^((?!(xyz|efg)).)*$', r'^.*[^,|.]$', r'^[a-zA-Z]{1,10}$')
for idx, str_item in enumerate(s_l):
    if all(re.match(r, str_item) for r in regexes):
        print(idx, "True")
    else:
        print(idx, "False")

您可以使用

import re
 
s_l = ['abcabcabcabc','defdef.','sssssss','def','def,','xyzabc,','efgdefefg']
 
for idx, str_item in enumerate(s_l):
    if re.match(r'^(?=abc|def)(?!.*(?:xyz|efg)).{1,10}$(?<![,.])', str_item): #find length of str smaller than 10
        print(idx, "True")
    else:
        print(idx, "False")

参见Python demo and the regex demo

详情:

  • ^ - 字符串开头
  • (?=abc|def) - 开头不允许 abcdef
  • (?!.*(?:xyz|efg)) - xyzefg 都不允许出现在除换行字符之外的任何零个或多个字符之后
  • .{1,10} - 除换行符以外的一到十个字符
  • $ - 字符串结尾
  • (?<![,.]) - 字符串末尾不允许 ,.