I want to extract digits from a short string, base on a condition that the digits is in front of a character (S
flag).
example and result:
JavaScript
x
9
1
> string = '10M26S'
2
> 26
3
4
> string = '18S8M10S'
5
> [18,10] OR 28
6
7
> string = '7S29M'
8
> 7
9
I can split the string to a list to get the individual element,
JavaScript
1
3
1
result = [''.join(g) for _, g in groupby('18S8M10S', str.isalpha)]
2
> ['18', 'S', '8', 'M', '10', 'S']
3
but how could I just get the 18
and 10
?
Advertisement
Answer
Use re.findall
with the regex r'(d+)S'
. This matches all digits before a capital S
.
JavaScript
1
10
10
1
>>> string = '10M26S'
2
>>> re.findall(r'(d+)S',string)
3
['26']
4
>>> string = '18S8M10S'
5
>>> re.findall(r'(d+)S',string)
6
['18', '10']
7
>>> string = '7S29M'
8
>>> re.findall(r'(d+)S',string)
9
['7']
10
To get integer output, you can convert them in a list comp or use map
JavaScript
1
3
1
>>> list(map(int,['18', '10']))
2
[18, 10]
3