Extracting an image ID from an image path

Viewed 26

how can I extract images id from image path. just want to take 10877 from this path /content/gdrive/MyDrive/new/batch/aligned_10877nationalIdFront.png

1 Answers
import re

path = "/content/gdrive/MyDrive/new/batch/aligned_10877nationalIdFront.png"

# It will return the first match only
x = re.search("[0-9]+", path)
print(x.group())


# or in case if there are multiple sets...
x = re.findall("[0-9]+", path)
print(x[0]) # x[0] for the first, x[1] for the second, and so on


# If "aligned_" is always there you may also do
x = re.findall("aligned_([0-9]+)", path)
print(x[0])

Please have a look at the re library documentation. It's very useful for many applications.

Related