Python regex for int with at least 4 digits -


i learning regex , i'm bit confused here. i've got string want extract int @ least 4 digits , @ 7 digits. tried follows:

>>> import re >>> teststring = 'abcd123efg123456' >>> re.match(r"[0-9]{4,7}$", teststring) 

where expecting 123456, unfortunately results in nothing @ all. me out little bit here?

@explosionpills correct, there still 2 problems regex.

first, $ matches end of string. i'm guessing you'd able extract int in middle of string well, e.g. abcd123456efg789 return 123456. fix that, want this:

r"[0-9]{4,7}(?![0-9])"             ^^^^^^^^^ 

the added portion negative lookahead assertion, meaning, "...not followed more numbers." let me simplify use of \d though:

r"\d{4,7}(?!\d)" 

that's better. now, second problem. have no constraint on left side of regex, given string abcd123efg123456789, you'd match 3456789. so, need negative lookbehind assertion well:

r"(?<!\d)\d{4,7}(?!\d)" 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -