Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to extract function from c++ function calls [duplicate]

Tags:

c++

regex

I have to extract a function name from various c++ function calls. Following are some of the function calls examples and extracted function names highlighted.

  • std::basic_fstream<char,std::char_traits<char> >::~basic_fstream<char,std::char_traits<char> > ~basic_fstream
  • CSocket::Send send
  • CMap<unsigned int,unsigned int &,tagLAUNCHOBJECT,tagLAUNCHOBJECT &>::RemoveAll Cerner::Foundations::String::Rep::~Rep~Rep

  • CCMessage::~CCMessage ~CCMessage

  • std::_Tree<std::_Tmap_traits<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,u_Tree
  • Lib::DispatcherCache::~DispatcherCache~DispatcherCache
  • CPrefDataObjectLoader<CPrefManagerKey,CPrefManagerValue,CGetPrefManager,PrefManagerKeyFunctor>::Get Get

    The following Regex works for most of the functions

  • /((?:[^:]*))$';/ This regex get the string from the last :
  • /+?(?=<)';/ This one removes string that starts with <

But for std::basic_fstream<char,std::char_traits<char> >::~basic_fstream<char,std::char_traits<char> > the output I get is char_traits because this string is after last ':' but the result should be ~basic_fstream. Is there a way I can combine both regex and ignore everything that is within <>?

like image 500
SS Sid Avatar asked Jun 19 '26 23:06

SS Sid


1 Answers

The grammar of C++ is not only not regular, it's actually highly context-sensitive (especially near templates). Even a proper CFG parser won't help you, let alone a plain old regex… Rather than trying to approximate the impossible using ugly and fragile hacks, why not use an actual tool for the job? If you want to parse C++, then use a C++ parser, such as libclang.

like image 149
The Paramagnetic Croissant Avatar answered Jun 21 '26 11:06

The Paramagnetic Croissant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!