Golang : How to tokenize source code with text/scanner package?
It has been a while since I touch the topic on tokenizer.....err... since the day I actually built a compiler back in the 90's in Ada95!
Ok, time to cut the grandma or grandpa story.
This short code example below demonstrate how to tokenize souce code with Golang's text/scanner
package.
Here you go !
package main
import (
"fmt"
"strings"
"text/scanner"
)
func main() {
code := `<?php
echo "Hello World!";
?>`
codeReader := strings.NewReader(code)
fmt.Println(code)
fmt.Println("------------------------------")
fmt.Println("TOKENS : ")
fmt.Println("------------------------------")
var scn scanner.Scanner
scn.Init(codeReader)
tok := scn.Scan()
fmt.Println(scn.TokenText())
for tok != scanner.EOF {
tok = scn.Scan()
fmt.Println(scn.TokenText())
}
}
Play at : http://play.golang.org/p/R9pDAt2jOO
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+13.3k Golang : How to determine if a year is leap year?
+6.9k Golang : File system scanning
+27.1k PHP : Count number of JSON items/objects
+19.3k Golang : Archive directory with tar and gzip
+5.1k Golang : If else example and common mistake
+18.2k Golang : Implement getters and setters
+9.4k PHP : Get coordinates latitude/longitude from string
+20.8k Golang : How to get time zone and load different time zone?
+24.6k Golang : Daemonizing a simple web server process example
+16.3k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+19.4k Golang : Determine if directory is empty with os.File.Readdir() function
+31.8k Golang : Copy directory - including sub-directories and files