I want to get the first #include
statement from a .cpp file using Python regex as fast as possible.
For example,
/* Copyright:
This file is
protected
#include <bad.h>
*/
// Include files:
#undef A_MACRO
#include <stddef.h> // defines NULL
#include "logger.h"
// Global static pointer used to ensure a single instance of the class.
Logger* Logger::m_pInstance = NULL;
should return #include <stddef.h>
I know one way is to remove all comments and then get the first line from the remaining texts. But this seems not to be fast enough since it has to go through the whole file. If I only need the first #include
statement, is there any efficient way I can do it using Python regex?
[Update 1] Several folks mentioned it's not a good solution to use regex. I understand this is not a typical use case of regex. But is there a better way to get rid of the leading comments than regex? Any suggestion would be appreciated.
[Update 2] Thanks for the answers. But seems there is no one I am satisfied yet. My requirements are straightforward: (1) avoid going through the whole file to get the first line. (2) Need to handle the leading comments correctly.
The get() method of the ArrayList class accepts an integer representing the index value and, returns the element of the current ArrayList object at the specified index. Therefore, if you pass 0 to this method you can get the first element of the current ArrayList and, if you pass list.
Write a JavaScript function to get the first element of an array. Passing a parameter 'n' will return the first 'n' elements of the array. ES6 Version: var first = (array, n) => { if (array == null) return void 0; if (n == null) return array[0]; if (n < 0) return []; return array.
1-based indexing, 0-based indexing. Note: In most programming languages, the first array index is 0 or 1, and indexes continue through the natural numbers. The upper bound of an array is generally language and possibly system specific.
To get the first element of a Set, use destructuring assignment, e.g. const [first] = set . The destructuring assignment sets the variable to the first element of the Set. Copied!
You can use a library called CppHeaderParser like this:
import sys
import CppHeaderParser
cppHeader = CppHeaderParser.CppHeader("test.cpp")
print("List of includes:")
for incl in cppHeader.includes:
print " %s" % incl
For it to work you should do
pip install cppheaderparser
It outputs:
List of includes:
<stddef.h> // defines NULL
"logger.h"
Certainly not the best result, but it's a start.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With