A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://yourbasic.org/golang/gotcha-regexp-substring/ below:

Is "three" a digit? · YourBasic Go

Is "three" a digit?

yourbasic.org/golang

Why does the regular expression [0-9]*, which is supposed to match a string with zero or more digits, match a string with characters in it?

matched, err := regexp.MatchString(`[0-9]*`, "12three45")
fmt.Println(matched) // true
fmt.Println(err)     // nil (regexp is valid)
Answer

The function regexp.MatchString (as well as most functions in the regexp package) does substring matching.

To check if a full string matches [0-9]*, anchor the start and the end of the regular expression:

matched, err := regexp.MatchString(`^[0-9]*$`, "12three45")
fmt.Println(matched) // false
fmt.Println(err)     // nil (regexp is valid)

See this Regexp in-depth tutorial for a cheat sheet and plenty of code examples.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4