Created
March 3, 2023 14:49
-
-
Save royvandam/36528dc38a67e2a2acc7f859206a62d0 to your computer and use it in GitHub Desktop.
Regex based C/C++ include parser in Golang capable of dealing with comments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"strings" | |
"bufio" | |
"regexp" | |
"fmt" | |
) | |
const test_data = ` | |
#include "want1.h" | |
#include <want2.h> | |
// #include <ignore.h> | |
/* #include "ignore.h" */ | |
/* #include "ignore.h" | |
*/ | |
/* alice */ /* bob */ #include "want3.h" /* clair */ /* /* | |
#include <ignore.h> | |
*/ | |
/* | |
#include <ignore.h> */ | |
/* | |
#include <ignore.h> | |
*/ | |
` | |
var reInclude = regexp.MustCompile(`(#include\s*['"<]([^'"<>]*)['">])|(/\*)|(\*/)|(//)`) | |
func main() { | |
inCommentBlock := false | |
sc := bufio.NewScanner(strings.NewReader(test_data)) | |
for sc.Scan() { | |
matches := reInclude.FindAllStringSubmatch(sc.Text(), -1) | |
matchLoop:for _, match := range matches { | |
switch { | |
// Matched include | |
case len(match[2]) != 0: | |
if inCommentBlock { | |
continue | |
} | |
fmt.Println(match[2]) | |
// Line comment | |
case len(match[5]) != 0: | |
if !inCommentBlock { | |
break matchLoop | |
} | |
// Block comment start | |
case len(match[3]) != 0: | |
inCommentBlock = true | |
// Block comment end | |
case len(match[4]) != 0: | |
inCommentBlock = false | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Godbolt demo: https://godbolt.org/z/Ec7bsGvMx