Puckpicker
Puckpicker

Reputation: 13

Regular expression to find even/odd number

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

Answers (3)

mikeb
mikeb

Reputation: 11287

Your re matches:

  1. Start of string
  2. 0 or more digits 0,1,2,3,4,5,6,7,8 or 9
  3. One even number
  4. End of string

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

madbird
madbird

Reputation: 1379

  1. In python you should not wrap expression with slashes ('/^[0-9]*[02468]$/' -> '^[0-9]*[02468]$')
  2. $ 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]')
  3. After that you need to stop matching only prefixes ('[0-9]*[02468]' -> r'[0-9]*[02468](?![0-9])')
  4. That's it :) enter image description here

Upvotes: 3

Trutch70
Trutch70

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

Related Questions