Using regular expressions to validate a numeric range

后端 未结 11 1722
自闭症患者
自闭症患者 2020-11-21 22:16

My input number is an int. But the input number must be in a range from -2055 to 2055 and I want to check this by using regular expression.

So is there anyway to wri

11条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-21 22:58

    So many answers, but noone reads (or cares) about the OPs side question in the comments?

    I'm writing an interpreter in OCaml .... how can i validate the input number within the range without using regex ?? – Trung Nguyen Mar 2 at 17:30

    As so many answers - correctly - pointed out that using regex is horrible for this scenario, lets think about other ways in OCaml! It is a while since I used OCaml, but with looking up a few constructs I was able to knock this together:

    let isInRange i = 
        not(i < -2055 or i > 2055);;
    
    let isIntAndInRange s = 
        try
        let i = int_of_string s in
        not(i < -2055 or i > 2055)
        with Failure "int_of_string" -> false;;
    
    let () = print_string "type a number: " in
    let s = read_line () in
    isIntAndInRange s
    

    If anything about is unclear, please read up on its syntax, type conversion functions and exception handling and input-output functions.

    The user input part is only used to demonstrate. It might be more convenient to use the read_int function there. But the basic concept of handling the exception stays the same.

提交回复
热议问题