Skip to content

Instantly share code, notes, and snippets.

@royvandam
Created March 3, 2023 14:49
Show Gist options
  • Save royvandam/36528dc38a67e2a2acc7f859206a62d0 to your computer and use it in GitHub Desktop.
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
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
}
}
}
}
@royvandam
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment