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
+6k PHP : Get client IP address
+5.4k Golang : Display advertisement images or strings on random order
+11.9k Golang : Determine if time variables have same calendar day
+5.7k Golang : Error handling methods
+20.8k Golang : Convert PNG transparent background image to JPG or JPEG image
+8.4k PHP : How to parse ElasticSearch JSON ?
+9.9k Golang : Check if user agent is a robot or crawler example
+21k Golang : Sort and reverse sort a slice of strings
+8.8k Golang : Accept any number of function arguments with three dots(...)
+15.5k Golang : Force download file example
+7.9k Golang : Handle Palindrome string with case sensitivity and unicode
+3.7k Java : Random alphabets, alpha-numeric or numbers only string generator