简体   繁体   English

JavaScript:小数点格式的正则表达式

[英]JavaScript: Regex on decimals formatting

In my current app, I am implementing field validation with regex for forms. 在我当前的应用程序中,我正在使用正则表达式为表单实现字段验证。

More specifically, I am having trouble handling edge-case for numbers with decimals. 更具体地说,我在处理带小数的数字的边缘情况时遇到麻烦。

Essentially I am using regex to prevent users from typing wrong information in to the input fields. 本质上,我使用正则表达式来防止用户在输入字段中键入错误的信息。

For instance, if user would type 12.2 and then . 例如,如果用户输入12.2然后输入. afterwards, I am using regex to detect what shouldn't be there, and replace with empty string, '' 之后,我使用正则表达式检测不应该存在的内容,并替换为空字符串, ''

Here's my current implementation using a call back function: 这是我当前使用回调函数的实现:

export const checkFormat = (typeFormat, value) => {
  //value is stringified
  switch (typeFormat) {
    //...
    case NUMERIC_DECIMALS: {
      return value.replace(/(\d+\.\d+)(\.*)\d*/g, '$1')
    }
  }

}

However, the current regex implementation can't handle such cases as 但是,当前的正则表达式实现无法处理以下情况

  • User types : . 用户类型: . , then .. ==> . ,然后.. ==> .
  • User types : 123.2 , then 1.23.2 ==> 1.232 用户类型: 123.2 ,然后1.23.2 ==> 1.232

I'm fairly new to Regex, so obviously it needs some work 我是Regex的新手,因此显然需要一些工作

You can try this: 您可以尝试以下方法:

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

and replace by this: 并替换为:

$1

Regex 101 demo 正则表达式101演示

Or to get the a more complex solution, which I guess you are looking for, you may try this: 或者要获得更复杂的解决方案(我想您正在寻找),可以尝试以下方法:

 const regex = /^(\\d+(?:\\.\\d*))|(\\.)?/gm; const str = ["1.2","...","g..g","1.23","1.2.3.4",".,",".,","123.2","1.23.2","14","1","15.6.4789756465","g"]; const replaceRegex = /[^\\.\\d]/gm; for(var i=0;i<str.length;i++) { var res=str[i].replace(replaceRegex,'').split(regex); var finalResult=""; var alreadyContainsDot=false; for(var j=0;j<res.length;j++) if(res[j]!=null && res[j]!="") { if(res[j].includes(".") && !alreadyContainsDot) alreadyContainsDot=true; else if(res[j].includes(".") && alreadyContainsDot) res[j]=res[j].replace(/\\./gm,''); finalResult+=res[j]; } console.log(str[i]+"==>"+finalResult); } 

If my interpretation of the requirement is correct, this should work: 如果我对需求的解释是正确的,那么应该可以:

const regex = /(\d+\.?\d+?)(\D+)/g;
const str = `131/1.13.ad`;
const subst = `$1`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

Regex101 link Regex101链接

It is bad UX practice to monitor what the user is typing and change his input out from underneath him. 监视用户正在键入的内容并从其下方更改其输入是不好的UX习惯。 He is likely to think his keyboard is broken. 他可能认为自己的键盘坏了。 I don't know when or how this approach became so widespread, but thankfully it seems to be dying out. 我不知道这种方法何时或如何如此普及,但值得庆幸的是它似乎正在消失。

In any case, it is always a bad idea to try to do things with numbers using regexps, which are fundamentally designed for manipulating strings. 无论如何,尝试使用正则表达式来处理数字始终是一个坏主意,而正则表达式是为处理字符串而设计的。 If for some reason you need to check if some string is a valid number, use numeric APIs such as !isNaN(+value) . 如果出于某些原因需要检查某个字符串是否为有效数字,请使用数字API,例如!isNaN(+value)

Use the appropriate type or pattern attributes on your input fields to do validation. 在输入字段上使用适当的typepattern属性进行验证。 If that does not suffice, validate when the user presses the "Submit" button or equivalent. 如果那还不够,请验证用户何时按下“提交”按钮或等效按钮。

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

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