Golang : How to check if input string is a word?
Problem :
I'm writing a parser and I need to determine if the user input is a word or something else? How to do that?
Solution :
Use the IsWordChar()
function from syntax/regexp
package. For example :
NOTE : This solution is for ASCII-only: the word characters are [A-Za-z0-9_].
package main
import (
"fmt"
"regexp/syntax"
)
func main() {
word1 := []rune("alpha")
word2 := rune('吃') // no need for array if for single rune
word3 := []rune("1234")
word4 := []rune(" $#$^@#$ ")
ok := syntax.IsWordChar(word1[0])
fmt.Printf("%v is a word ? : %v \n", string(word1), ok)
ok = syntax.IsWordChar(word2)
fmt.Printf("%v is a word ? : %v \n", string(word2), ok)
ok = syntax.IsWordChar(word3[0])
fmt.Printf("%v is a word ? : %v \n", string(word3), ok)
ok = syntax.IsWordChar(word4[0])
fmt.Printf("%v is a word ? : %v \n", string(word4), ok)
}
Output :
alpha is a word ? : true
吃 is a word ? : false
1234 is a word ? : true
$#$^@#$ is a word ? : false
Reference :
https://www.socketloop.com/references/golang-regexp-syntax-iswordchar-function-example
See also : Golang : How to tokenize source code with text/scanner package?
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
+48.2k Golang : Upload file from web browser to server
+13.1k Golang : Read from buffered reader until specific number of bytes
+4.5k Unix/Linux : How to pipe/save output of a command to file?
+28.2k Get file path of temporary file in Go
+13.5k Golang : Convert spaces to tabs and back to spaces example
+5.8k Golang : Compound interest over time example
+12.3k Golang : Remove or trim extra comma from CSV
+17.3k How to enable MariaDB/MySQL logs ?
+13.9k Golang : Chunk split or divide a string into smaller chunk example
+11.5k Golang : Verify Linux user password again before executing a program example
+19.7k Golang : Reset or rewind io.Reader or io.Writer
+6.3k Unix/Linux : How to get own IP address ?