I'm using React-native I made a regex that accepts only numbers. Here, I want to allow one minus at the beginning only. That is, I want to create a regular expression that allows "-" only once, but can be used or not. So I applied my code, but it doesn't work. How do I fix my regular expression?
The restriction is that the minus must not be placed in the middle of or after the number, only at the beginning of the number, and the minus can be used or not.
let minCheck = !/^[0-9]{1,4}$/g.test("-1")
i tried
let minCheck = /-?!/^[0-9]{1,4}$/g.test(valueRange.minValue)
but it doesn't work
How can i fix my code?
CodePudding user response:
Hopefully the following will fix your issue(in case you want to make minus sign compulosry):
/(-)([0-9]{1,4})/
In case you want to make minus sign optional, please try this:
/([-0-9]{1,4})/
If either of these don't work for you, please ask and I'll make one accordingly for you.
CodePudding user response:
You can use below regEx:
Exp 1: /^(-)?\d $/g.test("-213213")
Exp 2: /^(0|(-)?[1-9]\d*)$/g.test("12321")
- "-" with ? makes it non-mandatory
- d expects more than 1 digits
- Exp 1 allows start with 0 for ex: "-0" or "0123" will also be true. If you want to restrict that. Use Exp 2