Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

Hi I have a list of ids separated with commas and I need to take the ids which are divisible to 3.

share|improve this question

2 Answers 2

up vote 2 down vote accepted

This cannot be done with a regex in any useful way.

Depending on your context you can use for example

[i for i in my_ids.split(',') if int(i) % 3==0]

(assuming the string my_ids contains your ids)

share|improve this answer

This regexp will match all numbers divisible by three:

^([0369]|[147][0369]*([147][0369]*[258][0369]*)*([147][0369]*[147]|[258])|[258][0369]*([258][0369]*[147][0369]*)*([258][0369]*[258]|[147]))+$

Here is an example ipython session using this construct:

In [1]: import re

In [2]: my_ids = '1, 2, 3, 4, 5, 6, 7'

In [3]: idres = [x[0] for x in re.findall(r'\b([0369]|[147][0369]*([147][0369]*[258][0369]*)*([147][0369]*[147]|[258])|[258][0369]*([258][0369]*[147][0369]*)*([258][0369]*[258]|[147]))+\b', my_ids)]

In [4]: idres
Out[4]: ['3', '6']

This can be done, although – if you are sure that your input only contains comma-separated integer numbers (and not, say, words) – the answer from Florian Diesch contains a saner way to do this.

Differences: Florian's answer will convert everything that is separated by commas into integers (can cause problem when the input is not well-formed), divide them and return them as integer if they work. The regex version will just scan the input for any numbers divisible by three (that have word boundaries on both sides) and return them as strings.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.