如何在Go语言中使用正则表达式匹配特定范围内的所有内容?

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

How to match everything in certain bounds using regexp in go?

问题

我的目标是获取一个go函数的内容。

func开始,直到最后一个右花括号}

目前,我可以使用以下代码获取函数名:

re := regexp.MustCompile(`func (.*) `)

但我想获取整个函数的内容。

尝试过以下代码:

re := regexp.MustCompile(`func (.s)`)

但这个方法不起作用,我需要获取包括换行符在内的函数内容,直到函数末尾的最后一个右花括号。

编辑:
使用以下正则表达式成功获取函数:

re := regexp.MustCompile(`func(.*?)[\s\S]+?(func|\z)`)

但唯一的问题是它只获取了函数的一半(可能是由于第二个func)。有没有办法修改这个正则表达式以获取所有的函数?

英文:

My goal is to get the contents of a go function.

Starting from func till the last curly brace }.

Currently i can get the function name using below code:

re := regexp.MustCompile(`func (.*) `)

but i want to get the whole contents of the function.

Tried with:

re := regexp.MustCompile(`func (.s)`)

but this isn't working, need to get all the content with newlines till the last curly brace at the end of the function.

EDIT:
Manage to get the functions using this regex:

re := regexp.MustCompile(`func(.*?)[\s\S]+?(func|\z)`)

but only problem is that it is getting half of the functions(may be due to second func). Is there a way to tweak this regex to get all of the functions?

答案1

得分: 2

你不能这样做,你可以指示一个正则表达式在遇到第一个 } 时停止,但你想要的是计算你遇到了多少个 {,并在找到与 func { 匹配的 } 时停止。正则表达式无法为你完成这个任务。

相反,逐行读取文件并维护一个计数器,每遇到一个 { 就增加计数器,每遇到一个 } 就减少计数器,直到计数器为0为止。

或者使用一个实际的解析器,比如 go/parser

英文:

You can't do this, you can instruct a regex to stop at the first } it sees but what you wan't is to count how many { you have seen and stop when you find the } that matches the func {. Regexes can't do this for you.

Instead, read the file line by line and maintain a counter, increment for each { and decrement for each } util you hit 0.

Or use an actual parser like go/parser.

huangapple
  • 本文由 发表于 2022年4月14日 16:18:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/71868525.html
匿名

发表评论

匿名网友

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

确定