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
+12.8k Golang : Get query string value on a POST request
+3.2k Which content-type(MIME type) to use for JSON data
+40.9k Golang : Encode image to base64 example
+8.7k Swift : Convert (cast) String to Integer
+7.2k Golang : Go as a script or running go with shebang/hashbang style
+11.2k Golang : Convert(cast) int to int64
+14.5k Golang : Find smallest number in array
+7k Golang : Inject/embed Javascript before sending out to browser example
+7.8k Golang : Sort and reverse sort a slice of integers
+8.7k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+17.2k Golang : GORM create record or insert new record into database example