Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python Regex to Find C function in File

Tags:

python

c

regex

I am trying to get a Python regex to search through a .c file and get the function(s) inside it.

For example:

int blahblah(
  struct _reent *ptr __attribute__((unused)),
  const char    *old,
  const char    *new
)
{
...

I would want to get blahblah as the function.

This regex doesn't work for me, it keeps on giving me None: r"([a-zA-Z0-9]*)\s*\([^()]*\)\s*{"

like image 289
High schooler Avatar asked Feb 04 '26 06:02

High schooler


2 Answers

(?<=(int\s)|(void\s)|(string\s)|(double\s)|(float\s)|(char\s)).*?(?=\s?\()

http://regexr.com?3332t

This should work for what you want. Just keep adding types that you need to catch.

re.findall(r'(?<=(?<=int\s)|(?<=void\s)|(?<=string\s)|(?<=double\s)|(?<=float\s‌​)|(?<=char\s)).*?(?=\s?\()', string) will work for python.

like image 169
Jack Avatar answered Feb 05 '26 19:02

Jack


The regular expression isn't catching it because of the parentheses in the arguments (specifically, the parentheses in __attribute__((unused))). You might be able to adapt the regular expression for this case, but in general, regular expressions cannot parse languages like C. You may want to use a full-fledged parser like pycparser.

like image 32
icktoofay Avatar answered Feb 05 '26 18:02

icktoofay