I have strings like
uint8_t
char[5]
int[3]
How can I write a short function to get the type and length separately in an elegant way
for eg
uint8_t // return 'uint8_t', '1'
char[5] // return 'char', '5'
...
I have strings like
uint8_t
char[5]
int[3]
How can I write a short function to get the type and length separately in an elegant way
for eg
uint8_t // return 'uint8_t', '1'
char[5] // return 'char', '5'
...
In [1]: import re
In [2]: r = re.compile('([\w_]+)(?:\[(\d+)\])?')
In [3]: m = r.match('char[5]')
In [4]: m.group(1), m.group(2) or 1
Out[4]: ('char', '5')
In [5]: m = r.match('uint8_t')
In [6]: m.group(1), m.group(2) or 1
Out[6]: ('uint8_t', 1)
Making a function is left as an exercise to the reader.
import re
def parse_type(text):
match = re.match(r'(.+)\[(\d+)\]', text)
if match:
return match.groups()
return text, 1
print parse_type('uint8_t')
print parse_type('char[5]')
print parse_type('int[3]')
given these tests:
>>> s = "char[5]"
>>> p = s.split("[")
>>> p
['char', '5]']
>>> p[1].strip("]")
'5'
>>> s = "uint8_t"
>>> p = s.split("[")
>>> p
['uint8_t']
>>>
here's a little function that gives you what you want:
def SplitNicely(s):
p = s.split("[")
if len(p) == 1:
size = 1
else:
size = int(p[1].strip("]"))
return p[0], size
more error checking would be useful too
Let's make it a one-liner:
import re
def type_and_size(s):
return re.split('[][]', s+'[1]', 2)[:2]
type_and_size('char')
['char', '1']
type_and_size('char[5]')
['char', '5']
Obviously you can do:
type, size = type_and_size('char[5]')