Reputation: 13
I used codes below to find out even numbers from a string and returned nothing.
could anyone tell me what I missed? Thank you very much.
import re
str2 = "adbv345hj43hvb42"
even_number = re.findall('/^[0-9]*[02468]$/', str2 )
Upvotes: 0
Views: 808
Reputation: 11287
Your re matches:
That does not match your string, you should drop the begin of string ^
and end of string $
markers
To find an even number, just match any number of digits that ends with an even number '/[0-9]*02468/'
Upvotes: 2
Reputation: 1379
'/^[0-9]*[02468]$/'
-> '^[0-9]*[02468]$'
)$
and ^
are used to match the beginning and the end of string (or line in MULTILINE regex). But your example doesn't look you need to ('^[0-9]*[02468]$''
-> '[0-9]*[02468]'
)'[0-9]*[02468]'
-> r'[0-9]*[02468](?![0-9])'
)Upvotes: 3
Reputation: 133
Not sure what exactly you want to extract from the string, but in order to match single even numbers use such syntax: [02468]
(find one of the present in the list).
Upvotes: 1