Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
954 views
in Technique[技术] by (71.8m points)

python - Regex question about parsing method signature

I'm trying to parse a method signature that is in this format:

'function_name(foo=<str>, bar=<array>)'

From this, I want the name of the method, and each argument and it's type. Obviously I don't want the <, > characters, etc. The number of parameters will be variable.

My question is: How is it possible to get all the parameters when using this regex? I'm using Python, but I'm just looking for a general idea. Do I need named groups and, if so, how can I use them to capture multiple parameters, each with it's type, all in one regex?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't match a variable number of groups with Python regular expressions (see this). Instead you can use a combination of regex and split().

>>> name, args = re.match(r'(w+)((.*))', 'function_name(foo=<str>, bar=<array>, baz=<int>)').groups()
>>> args = [re.match(r'(w+)=<(w+)>', arg).groups() for arg in args.split(', ')]
>>> name, args
('function_name', [('foo', 'str'), ('bar', 'array'), ('baz', 'int')])

This will match a variable number (including 0) arguments. I have chosen not to allow additional whitespace, although you should allow for it by adding s+ between identifiers if your format isn't very strict.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...