In [1]:
import re
In [2]:
s = 'file5.txt'
In [3]:
print(re.search(r'\d+', s).group())
In [4]:
print(type(re.search(r'\d+', s).group()))
In [5]:
print(type(int(re.search(r'\d+', s).group())))
In [6]:
l = ['file10.txt', 'file1.txt', 'file5.txt']
In [7]:
print(sorted(l))
In [8]:
print(sorted(l, key=lambda s: int(re.search(r'\d+', s).group())))
In [9]:
p = re.compile(r'\d+')
print(sorted(l, key=lambda s: int(p.search(s).group())))
In [10]:
s = '100file5.txt'
In [11]:
print(re.search(r'\d+', s).group())
In [12]:
print(re.findall(r'\d+', s))
In [13]:
print(re.findall(r'\d+', s)[1])
In [14]:
print(re.search(r'file(\d+)', s).groups())
In [15]:
print(re.search(r'file(\d+)', s).groups()[0])
In [16]:
print(re.search(r'(\d+)\.', s).groups()[0])
In [17]:
l = ['100file10.txt', '100file1.txt', '100file5.txt']
In [18]:
print(sorted(l, key=lambda s: int(re.findall(r'\d+', s)[1])))
In [19]:
print(sorted(l, key=lambda s: int(re.search(r'file(\d+)', s).groups()[0])))
In [20]:
print(sorted(l, key=lambda s: int(re.search(r'(\d+)\.', s).groups()[0])))
In [21]:
p = re.compile(r'file(\d+)')
print(sorted(l, key=lambda s: int(p.search(s).groups()[0])))
In [22]:
l = ['file10.txt', 'file1.txt', 'file5.txt', 'file.txt']
In [23]:
# print(sorted(l, key=lambda s:int(re.search(r'\d+', s).group())))
# AttributeError: 'NoneType' object has no attribute 'group'
In [24]:
def extract_num(s, p, ret=0):
search = p.search(s)
if search:
return int(search.groups()[0])
else:
return ret
In [25]:
p = re.compile(r'(\d+)')
In [26]:
print(extract_num('file10.txt', p))
In [27]:
print(extract_num('file.txt', p))
In [28]:
print(extract_num('file.txt', p, 100))
In [29]:
print(sorted(l, key=lambda s: extract_num(s, p)))
In [30]:
print(sorted(l, key=lambda s: extract_num(s, p, float('inf'))))
In [31]:
l = ['100file10.txt', '100file1.txt', '100file5.txt', '100file.txt']
In [32]:
p = re.compile(r'file(\d+)')
print(sorted(l, key=lambda s: extract_num(s, p)))
In [33]:
print(sorted(l, key=lambda s: extract_num(s, p, float('inf'))))