简体   繁体   中英

Repeated Number in Python Regular expression

I'm trying to write a function to find weather a sentence has a particular number (ie: 1) but not any other number containing two or more 1 digits (ie: 11, 101, 111).

Should return 1 if the word is "something1.jpg" should return None if the word is "something11.jpg"

I have tried:

i = 1
word = "Actin11.png"
pattern = str(i) + "(?!" + str(i) + ")"
patComp = re.compile(pattern)

compiles but return 1 on "Actin11.png". I guess because it recognizes the one followed but the dot.

You can use count

i = str(1) 
word = "Actin11.png"
A=word.count(i)

if A==1:
    print "do something"
else:
    print word +" has zero or more than one " +i
def foo(i, word):
    i = str(i)
    if 2*i in word:
        return None
    return 1

IF I a am understanding what you want, it is a single digit without being proceeded / followed by another digit.

If so, you can do:

>>> st='3 eaxmple1.jpg example22.jpg 4'
>>> re.findall(r'(?:\D|^)(\d)(?:\D|$)', st)
['3', '1', '4']

Or, a negative lookahead and negative look behind:

>>> re.findall(r'(?<!\d)(\d)(?!\d)', st)
['3', '1', '4']

Try this way,

import re


def find_match(jpg):
    pat = "\d+"
    x = re.search(pat, jpg)
    if x:
        if x.group(0) == '1':
            return 1
        elif x.group(0) == '11':
            return None
    else:
        return "Not matched"

print find_match("Actin11.png")
print find_match("Actin1.png")

One regex to do that (check there is no more than one of your digit in the string) would be

(?!1.*1)

So if you want to build it dynamically,

pattern = r"(?!" + str(i) + r".*" + str(i) + r")"

FYI, your regex is failing because 1(?!1) matches the 1. part of Actin11.png .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM