0
votes

I'm looking for a regex in JavaScript that will select all non-digit characters except a single dot and a single dash. I tried [^0-9\.\-]+ but it doesn't select multiple dots or dashes. So it should select .. but not .

My use case is numeric input validation. A user can type any digit or single dot or single dash. And I will replace invalid inputs with an empty string.

1
could you post examples of input with matched substrings? - mrzasa
Your description is unclear. How would you use such a regex? (Is this an XY problem?) - melpomene
Does that mean -.- is valid input but -- is not? - melpomene
@melpomene, you're right, -.- should be also invalid. It adds complexity :) - Andrey
So you really just want to make sure that the input is a valid integer or float, which means a single dot or dash should also be invalid? If so, I wouldn't bother with a regex. Just use parseFloat(input_data) and see if you get NaN - user9366559

1 Answers

3
votes

You should be able to use the following :

(?:[^0-9\.\-]|\.{2,}|-{2,})+

It matches either characters that aren't digits nor .or -, or sequences of two or more . or -.

That alternation is put inside a (?:non-capturing group) in order to repeat it with the quantifier + without creating an useless capturing group.

Note that you don't have to escape . in a character class nor the - at the first or last position of a character class : (?:[^0-9.-]|\.{2,}|-{2,})+ should work just as well.

Regex101 sample.