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
+8.8k Golang : Check a web page existence with HEAD request example
+25.1k Golang : Calculate future date with time.Add() function
+11.7k Generate salted password with OpenSSL example
+12.8k Golang : Simple word wrap or line breaking example
+6.3k Golang : How to stop user from directly running an executable file?
+16.6k Golang : Get all upper case or lower case characters from string example
+4.9k Golang : Launching your executable inside a console under Linux
+5k Fix ERROR 2003 (HY000): Can't connect to MySQL server on 'IP address' (111)
+20.5k Golang : Use TLS version 1.2 and enforce server security configuration over client
+12k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+11.3k Golang : Remove or trim extra comma from CSV
+21.1k Golang : How to read JPG(JPEG), GIF and PNG files ?