Reputation: 1243
I have a list of comma-separated ids(digits) . And I need to get only these which are divisible by 3.
Example:
i = "3454353, 4354353, 345352, 2343242, 2343242 ..."
Upvotes: 3
Views: 10874
Reputation: 41
A hopefully complete version, from reduction of DEA[1]:
^([0369]|[147][0369]*[258]|(([258]|[147][0369]*[147])([0369]|[258][0369]*[147])*([147]|[258][0369]*[258])))+$
[1:] Converting Deterministic Finite Automata to Regular Expressions', C. Neumann 2005
NOTE: There is a typo in Fig.4: the transition from q_j
to itself should read ce*b
instead of ce*d
.
Upvotes: 4
Reputation: 336128
Just for the heck of it:
reobj = re.compile(
r"""\b # Start of number
(?: # Either match...
[0369]+ # a string of digits 0369
| # or
[147] # 1, 4 or 7
(?: # followed by
[0369]*[147] # optional 0369s and one 1, 4 or 7
[0369]*[258] # optional 0369s and one 2, 4 or 8
)* # zero or more times,
(?: # followed by
[0369]*[258] # optional 0369s and exactly one 2, 5 or 8
| # or
[0369]*[147] # two more 1s, 4s or 7s, with optional 0369s in-between.
[0369]*[147]
)
| # or the same thing, just the other way around,
[258] # this time starting with a 2, 5 or 8
(?:
[0369]*[258]
[0369]*[147]
)*
(?:
[0369]*[147]
|
[0369]*[258]
[0369]*[258]
)
)+ # Repeat this as needed
\b # until the end of the number.""",
re.VERBOSE)
result = reobj.findall(subject)
will find all numbers in a string that are divisible by 3.
Upvotes: 18
Reputation: 13222
Using the idea from this question i get:
i = "1, 2, 3, 4, 5, 6, 60, 61, 3454353, 4354353, 345352, 2343241, 2343243"
for value in i.split(','):
result = re.search('^(1(01*0)*1|0)+$', bin(int(value))[2:])
if result:
print '{} is divisible by 3'.format(value)
But you don't want to use regular expressions for this task.
Upvotes: 2
Reputation: 214949
If you really mean digits (not numbers), this is as easy as
re.findall(r'[369]', my_str)
For a list of numbers, it's quite easy without regular expressions:
lst = "55,62,12,72,55"
print [x for x in lst.split(',') if int(x) % 3 == 0]
Upvotes: 10