简体   繁体   中英

Select all non-digit characters except single dot and single dash

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM