It looks the following works, is it a good approach?
var thestr = "192.168.0.1"
if (thestr[0]>= '0' && thestr[0] <= '9'){
//...
}
Since you are comparing by character and no characters are between 1 and 9, I think your solution is ok, but it does not account for the other numbers following.
For example, if thestr
was "192.something.invalid"
it's no longer an IP.
I'd recommend using a regular expression to check the IP.
something like
\b(?:\d{1,3}\.){3}\d{1,3}\b
Please do not use regexps for that simple task :)
What I would change in this case:
.5e-45
is a number, but probably it is not what you want. 0's semantic is also not simple: https://math.stackexchange.com/questions/238737/why-do-some-people-state-that-zero-is-not-a-numberYour solution is completely fine.
But note that strings in Go are stored as a read-only byte slice where the bytes are the UTF-8 encoded byte sequence, and indexing a string indexes its bytes, not its runes (characters). But since a decimal digit ('0'..'9'
) has exactly one byte, it is ok in this case to test the first byte
, but first you should test if len(s) > 0
or s != ""
.
Here are some other alternatives, try all on the Go Playground:
This is your solution, probably the fastest one:
s := "12asdf"
fmt.Println(s[0] >= '0' && s[0] <= '9')
fmt.Sscanf()
:Note: this also accepts if the string
starts with a negative number, decide if it is a problem for you or not (e.g. accepts "-12asf"
).
i := 0
n, err := fmt.Sscanf(s, "%d", &i)
fmt.Println(n > 0, err == nil) // Both n and err can be used to test
unicode.IsDigit()
:fmt.Println(unicode.IsDigit(rune(s[0])))
regexp
:I would probably never use this as this is by far the slowest, but here it is:
r := regexp.MustCompile(`^\d`)
fmt.Println(r.FindString(s) != "")
Or:
r := regexp.MustCompile(`^\d.*`)
fmt.Println(r.MatchString(s))