简体   繁体   English

选择所有非数字字符,单点和破折号除外

[英]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. 我正在寻找JavaScript中的正则表达式,它将选择除单个点和单个破折号之外的所有非数字字符。 I tried [^0-9\\.\\-]+ but it doesn't select multiple dots or dashes. 我尝试了[^0-9\\.\\-]+但没有选择多个点或破折号。 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. 将该替换置于(?:non-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. 在字符类也不是-在字符类的第一或最后一个位置: (?:[^0-9.-]|\\.{2,}|-{2,})+应该工作一样好。

Regex101 sample . Regex101样本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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