Golang:在代码中静态查找所有字符串。

huangapple go评论73阅读模式
英文:

Golang: statically finding all strings in code

问题

我想解析一个包并输出代码中的所有字符串。具体的用例是收集 SQL 字符串并通过 SQL 解析器运行它们,但这是一个单独的问题。

最好的方法是逐行解析吗?还是可能使用正则表达式或其他方法?我想象有些情况可能不太简单,比如多行字符串:

str := "This is
the full
string"

// 希望得到 > This is the full string
英文:

I would like to parse a package and output all of the strings in the code. The specific use case is to collect sql strings and run them through a sql parser, but that's a separate issue.

Is the best way to do this to just parse this line by line? Or is it possible to regex this or something? I imagine that some cases might be nontrivial, such as multiline strings:

str := "This is
the full
string"

// want > This is the full string

答案1

得分: 2

使用go/scanner包来扫描Go源代码中的字符串:

src, err := os.ReadFile(fname)
if err != nil {
    // 处理错误
}

// 创建*token.File进行扫描。
fset := token.NewFileSet()
file := fset.AddFile(fname, fset.Base(), len(src))

var s scanner.Scanner
s.Init(file, src, nil, 0)

for {
    pos, tok, lit := s.Scan()
    if tok == token.EOF {
        break
    }
    if tok == token.STRING {
        s, _ := strconv.Unquote(lit)
        fmt.Printf("%s: %s\n", fset.Position(pos), s)
    }
}

https://go.dev/play/p/849QsbqVhho

英文:

Use the go/scanner package to scan for strings in Go source code:

src, err := os.ReadFile(fname)
if err != nil {
	/// handle error
}

// Create *token.File to scan.
fset := token.NewFileSet()
file := fset.AddFile(fname, fset.Base(), len(src))

var s scanner.Scanner
s.Init(file, src, nil, 0)

for {
	pos, tok, lit := s.Scan()
	if tok == token.EOF {
		break
	}
	if tok == token.STRING {
		s, _ := strconv.Unquote(lit)
		fmt.Printf("%s: %s\n", fset.Position(pos), s)
	}
}

https://go.dev/play/p/849QsbqVhho

huangapple
  • 本文由 发表于 2022年5月13日 07:53:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/72223172.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定