Expanding an alphanumeric range given a list
Question:
I have a list of alphanumeric items:
values=['1111X0-1111X3', 'A111X0-A111X3',...., ]
I would like to expand the last digit of every item in this list such that:
values_output = ['111X0', '111X1', '111X2', '111X3', 'A111X0', 'A111X1', 'A111X2', 'A111X3',...' ',...]
I found this answer on a similar post that uses regex:
import re
lst = ['4276-4279', 'I69-I71', 'V104-V112', '11528']
new = []
for l in lst:
m = re.match(r'^([A-Z]*)(d+)-1(d+)$', l)
if m:
new += [m.group(1) + str(i) for i in range(int(m.group(2)), int(m.group(3))+1)]
else:
new += [l]
print(new)
However I could not figure out a pattern to match the items on my list.
Any input is greatly appreciated!
Answers:
You can use
re.search(r'^(w+?)(d+)-1(d+)$', l)
See the Python demo.
Details:
^
– start of string
(w+?)
– Group 1: any one or more word chars as few as possible
(d+)
– Group 2: one or more digits
-
– a hyphen
1
– Group 1 value
(d+)
– Group 3: one or more digits
$
– end of string.
I have a list of alphanumeric items:
values=['1111X0-1111X3', 'A111X0-A111X3',...., ]
I would like to expand the last digit of every item in this list such that:
values_output = ['111X0', '111X1', '111X2', '111X3', 'A111X0', 'A111X1', 'A111X2', 'A111X3',...' ',...]
I found this answer on a similar post that uses regex:
import re
lst = ['4276-4279', 'I69-I71', 'V104-V112', '11528']
new = []
for l in lst:
m = re.match(r'^([A-Z]*)(d+)-1(d+)$', l)
if m:
new += [m.group(1) + str(i) for i in range(int(m.group(2)), int(m.group(3))+1)]
else:
new += [l]
print(new)
However I could not figure out a pattern to match the items on my list.
Any input is greatly appreciated!
You can use
re.search(r'^(w+?)(d+)-1(d+)$', l)
See the Python demo.
Details:
^
– start of string(w+?)
– Group 1: any one or more word chars as few as possible(d+)
– Group 2: one or more digits-
– a hyphen1
– Group 1 value(d+)
– Group 3: one or more digits$
– end of string.