0

I have an array having values as following : ['1.hello', '10.hel', '12B.hepl', '9.hell', '12A.help', '2.helo']

I want these sorted as : ['1.hello', '2.helo', '9.hell', '10.hel', '12A.help', '12B.hepl']

Any regex solution would also be preferred. Anything after the . is not to be considered for sorting the array

1 Answers1

1

Just fint the first number sequence and cast it to int:

import re
def get_sorting(s):
    s = re.findall(r'^\d+[A-Z]\.', s)[0].rstrip('.')
    num = int(s[:-1])
    return num, s[-1]

arr = sorted(arr, key = get_sorting)

update

As suggested By @ Raj006 in comments if you want it to support many letters after number use below function instead :

def get_sorting(s):
    a = re.match('(\d+)([A-Z]*)\.', s) 
    number = int(a.group(1)) 
    text = a.group(2)
    return number,text
adir abargil
  • 4,784
  • 1
  • 16
  • 23