0

I have a list of git branches in Python.

['fb_fix', 'master', 'rel.100.0', 'rel.101.0', 'rel.96.0', 'rel.96.2', 'rel.96.2.0', 'rel.97.0']

I need a regular expression via re module, which will include all the list items where there is prefix rel. and any numbers by masks 00.0 or 00.0.0 or 000.0 or 000.0.0, i.e. exclude other values from the list, in my example this is 'fb_fix' and 'master':

['rel.100.0', 'rel.101.0', 'rel.96.0', 'rel.96.2', 'rel.96.2.0', 'rel.97.0']

import subprocess

git_branches = subprocess.run("git branch -r", shell=True, stdout=subprocess.PIPE, encoding='utf-8')
branches_str = git_branches.stdout.replace("origin/", "")

branches_list = branches_str.split()
print(branches_list)

3 Answers 3

1

Use a list comprehension:

inp = ['fb_fix', 'master', 'rel.100.0', 'rel.101.0', 'rel.96.0', 'rel.96.2', 'rel.96.2.0', 'rel.97.0']
output = [x for x in inp if re.search(r'^rel\.\d+(?:\.\d+){1,2}', x)]
print(output)

This prints:

['rel.100.0', 'rel.101.0', 'rel.96.0', 'rel.96.2', 'rel.96.2.0',
 'rel.97.0']

Edit:

Assuming that the value rel is in some string variable, then we can try dynamically building the regex pattern here:

prefix = 'rel'
regex = r'^' + prefix + r'\.\d+(?:\.\d+){1,2}'
inp = ['fb_fix', 'master', 'rel.100.0', 'rel.101.0', 'rel.96.0', 'rel.96.2', 'rel.96.2.0', 'rel.97.0']
output = [x for x in inp if re.search(regex, x)]
print(output)  # same output as above
Sign up to request clarification or add additional context in comments.

6 Comments

Hi Tim. Thank you for your quick answer. Can I do prefix rel like variable?
Are you saying that you have some variable with the value 'rel' and you want to build the regex pattern dynamically?
Absolutely right. I tried to re.search(r"^\\{}\.\d+(?:\.\d+){1,2}".format(prefix), branch) Perhaps I need to escape characters
@DenisMozhaev Check the updated answer above.
Thanks Tim. prefix = "rel" regex = r"^" + prefix + r"\.\d+(?:\.\d+){1,2}" b = [branch for branch in branches_list if re.search(regex, branch)]
|
0

You can use the lambda:

filtered = filter(lambda k: 'rel' in k, branches_list)

Comments

0

Hey you can make use of the filter function plus re.compile just like so-

import re

git_branches = ['fb_fix', 'master', 'rel.100.0', 'rel.101.0', 'rel.96.0', 'rel.96.2', 'rel.96.2.0', 'rel.97.0']

r = re.compile('^(rel.*)')
my_branches = filter(r.match, git_branches)
print(list(my_branches))

the output of the code about is this ->

>>> ['rel.100.0', 'rel.101.0', 'rel.96.0', 'rel.96.2', 'rel.96.2.0', 'rel.97.0']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.