javascript 正则表达式只允许文本框中的一个点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25053605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:48:44  来源:igfitidea点击:

Regex to allow only a single dot in a textbox

javascriptjqueryregex

提问by Arjun Prajapati

I have one text input.

我有一个文本输入。

I wrote a regex for masking all special characters except .and -. Now if by mistake the user enters two .(dots) in input, then with the current regex

我写了一个正则表达式来屏蔽除.and之外的所有特殊字符-。现在,如果用户错误地在输入中输入了两个.(点),则使用当前的正则表达式

var valueTest='225..36'

valueTest.match(/[^-.\d]/)

I expected that the number will not pass this condition

我预计这个数字不会通过这个条件

How to handle this case. I just want one.(dot) in input field since it is a number.

这个案子怎么处理。我只想要输入字段中的一个.(点),因为它是一个数字。

回答by Avinash Raj

I think you mean this,

我想你是这个意思,

^-?\d+(?:\.\d+)?$

DEMO

演示

It allows positive and negative numbers with or without decimal points.

它允许带或不带小数点的正数和负数。

EXplanation:

解释:

  • ^Asserts that we are at the start.
  • -?Optional -symbol.
  • \d+Matches one or more numbers.
  • (?:start of non-capturing group.
  • \.Matches a literal dot.
  • \d+Matches one or more numbers.
  • ?Makes the whole non-capturing group as optional.
  • $Asserts that we are at the end.
  • ^断言我们处于开始阶段。
  • -?可选-符号。
  • \d+匹配一个或多个数字。
  • (?:非捕获组的开始。
  • \.匹配一个文字点。
  • \d+匹配一个或多个数字。
  • ?使整个非捕获组成为可选的。
  • $断言我们到了最后。

回答by Tim.Tang

if you just want to handle number ,you can try this:

如果你只是想处理 number ,你可以试试这个:

valueTest.match(/^-?\d+(\.\d+)?$/)

回答by Mena

You can probably avoid regex altogether with this case.

在这种情况下,您可能可以完全避免使用正则表达式。

For instance

例如

String[] input = { "225.36", "225..36","-225.36", "-225..36" };
for (String s : input) {
    try {
        Double d = Double.parseDouble(s);
        System.out.printf("\"%s\" is a number.%n", s);
    }
    catch (NumberFormatException nfe) {
        System.out.printf("\"%s\" is not a valid number.%n", s);
    }
}

Output

输出

"225.36" is a number.
"225..36" is not a valid number.
"-225.36" is a number.
"-225..36" is not a valid number.

回答by Mitul

Use below reg ex it will meet your requirements.

使用下面的 reg ex 它将满足您的要求。

/^\d+(.\d+)?$/

/^\d+(.\d+)?$/