сопоставление с образцом в пересечении списка в Python 3 - PullRequest
0 голосов
/ 27 апреля 2018

Я новичок в Python, и моя цель - написать хук предварительного получения, находящийся на git-сервере.

Хук должен проверять формат сообщений фиксации и отклонять push, если какое-либо из сообщений не проходит проверку формата.

Я думаю, что этот бит работает для простого сравнения шаблонов коммитов, как показано ниже:

commit_list = ['test1', 'test2', 'test3', 'test4']
patterns = ['test1','test2']

matched = set(commit_list).intersection(patterns) # find matches

for match in matched:
    commit_list[:] = (commit for commit in commit_list if commit != match) # remove matches from commit_list

commit_list_length = len(commit_list)

if commit_list_length == 0: # all commits matched so the list is empty
    print('all commit messages match the format')
else:
    print('%s of the commit messages don\'t match the format' % commit_list_length)
    print(commit_list)

Как мне изменить этот фрагмент, чтобы включить регулярное выражение, например: re.match(pattern,commit)?

Так что он все еще работает, когда вторая строка меняется на, например:

patterns = ['test[0-9]{1,5}','test: ']

Ответы [ 2 ]

0 голосов
/ 27 апреля 2018

Я думаю, что нашел рабочее решение, хотя, почти наверняка, не самое короткое и не самое эффективное:

commit_list = ['test1', 'test234', 'testA', 'test:a', 'test: a']
patterns = ['test[0-9]{1,5}','test: ']

cloned_list = list(commit_list) # copy list of commits

for item in commit_list:
    for pattern in patterns:
        if re.match(pattern,item):
            cloned_list.remove(item) # work on the copy and discard matched
        elif not re.match(pattern,item):
            continue # exhaust all possibilities

cloned_list_length = len(cloned_list)

if cloned_list_length == 0: # all commits matched so the list is empty
    print('all commit messages match the format')
else:
    print('%s of the commit messages don\'t match the criteria' % cloned_list_length)
    print(cloned_list) # only print unmatched

все еще готов попробовать лучшие предложения!

0 голосов
/ 27 апреля 2018

Если вы хотите изменить код для включения re.match(), вы можете попробовать это.

import re
commit_list = ['test1', 'test2', 'test3', 'test4']
patterns = ['test1','test2']
regx=re.compile(r'{}'.format("|".join(patterns)))
commit_unmatched=[commit for commit in commit_list if not regx.match(commit)]
print(commit_unmatched)
...