F # check if string contains only number

I am trying to find a good way to check if a string contains only a number. This is the result of my efforts, but it seems really verbose:

let isDigit c = Char.IsDigit c

let rec strContainsOnlyNumber (s:string)=
    let charList = List.ofSeq s
    match charList with
        | x :: xs -> 
            if isDigit x then
                strContainsOnlyNumber ( String.Concat (Array.ofList xs))
            else 
                false
        | [] -> true

for example, it seems very ugly that I need to convert a string to a char list and then go back to the string. Can you find a better solution?

+4
source share
1 answer

There are several different options for this.

Given what System.Stringthe sequence of characters you currently use to turn into a list is, you can skip the conversion of lists and just use it Seq.forallfor direct testing:

let strContainsOnlyNumber (s:string) = s |> Seq.forall Char.IsDigit

, , :

let strContainsOnlyNumber (s:string) = System.Int32.TryParse s |> fst

, true , "-342" ( -, ).

:

let numberCheck = System.Text.RegularExpressions.Regex("^[0-9]+$")    
let strContainsOnlyNumbers (s:string) = numberCheck.IsMatch s

, , .

, , , :

let tryToInt s = 
    match System.Int32.TryParse s with
    | true, v -> Some v
    | false, _ -> None

, ( Option.isSome), , .

, - Int32.TryParse Double.TryParse, float.

+3

Source: https://habr.com/ru/post/1669838/


All Articles