'How to match everything in certain bounds using regexp in go?
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?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dylan Reimerink |
