regular expression
Sean 'Shaleh' Perry
shalehperry at attbi.com
Sat May 18 13:46:19 EDT 2002
On 18-May-2002 Batara Kesuma wrote:
> Hi,
>
> I tried to look at the docs, but couldn't get it.
>
> How can I compile the regex rule, and match a list? I want to print out
> only list that contains 6 digits in it.
>
> --- start ---
>
> import re
> list = ['123456', '234567', '123', 'abc', '1234567']
>
> for x in list:
> rule = re.compile(\d{6,6}) // here I don't know...
> if rule.match(x):
> print x
>
> --- end ---
>
you are very close to what you need.
rule = re.compile(r'^\d{6}$') # ^ means start of string, then \d{6} is 6 numbers
# then $ is end of string.
for x in list: # btw, naming a list 'list' is a bad idea
if rule.match(x):
print x
or
good = filter(rule.match, list)
for x in good:
print x
More information about the Python-list
mailing list