简体   繁体   English

JavaScript正则表达式:如何让oninput模式中只有2个十进制浮点数匹配?

[英]JavaScript Regex: How to let only 2 decimal floating number through oninput pattern match?

I have an input type="text" with an input event handler attached to it, which i would like to use to overwrite the input.value with a "filtered" result of the users' key presses. 我有一个附加了输入事件处理程序的输入type =“ text”,我想用它通过用户按键的“过滤”结果覆盖input.value。

Basically i want to write a regular expression that only allows floating numbers (positive or negative) with (optionally) 2 decimal positions. 基本上我想写一个只允许(可选)2个小数位的浮点数(正数或负数)的正则表达式。

Here's a scripted example of what i'm looking for. 这是我要寻找的脚本示例

If you hit any key while focusing the input in the example above, the input value will be filtered using a combination of regex and JavaScript. 如果您在上面的示例中集中输入时按下任意键,则将使用正则表达式和JavaScript的组合来过滤输入值。

My test input currently looks like this: 我的测试输入当前看起来像这样:

<input type="text" id="test" value="-3c.fvbnj23.79.8fbak-cfb436.sdafosd8r32798s.hdf-5kasjfds-gf..">

The input event handler looks like this: 输入事件处理程序如下所示:

document.getElementById('test').oninput = function(){
  var foundDot = false,
      str = '';

  this.value.replace(/^-|\.(?=\d)|\d*/g, function(match){
    if (match === '.' && foundDot === true) {
      return;
    }

    if (match === '.' && foundDot === false) foundDot = true;

    str += match;
  });

  this.value = parseFloat(str).toFixed(2);
}

Is it possible to obtain the same result with a regular expressions only? 仅使用正则表达式能否获得相同的结果?

Even better, it can be done without regex at all. 更好的是,完全不需要正则表达式就可以完成。

Well, okay, one regex. 好吧,一个正则表达式。 I misunderstood that you wanted to preserve digits within non-numeric strings. 我误解了您想保留非数字字符串中的数字。

All right, fiiiiine, two regexes. 好吧,fiiiiine,两个正则表达式。 ¯\\_(ツ)_/¯ ¯\\ _(ツ)_ /¯

 //oninput is too aggressive, it runs on every keystroke making it difficult to type in longer values. document.getElementById('test').onchange = function(){ // strip non-numeric characters. // First char can be -, 0-9, or . // Others can only be 0-9 or . var val = this.value.replace(/(?!^[\\-\\d\\.])[^\\d\\.]/g,''); // strip out extra dots. Here I admit regex defeat and resort to slice-and-dice: var firstDot = this.value.indexOf('.'); if (firstDot > -1) { val = val.substr(0,firstDot+1) + val.substring(firstDot+1).replace(/\\./g,'') } console.log(val); // Finally the easy part: set the precision this.value = parseFloat(val).toFixed(2); } 
 <input id="test"> 

I don't know why you can't just use a find/replace on each keystroke. 我不知道为什么您不能仅对每个按键使用查找/替换。

Find ^([-+]?(?:\\d+(?:\\.\\d{0,2})?|\\.\\d{0,2})?) 找到^([-+]?(?:\\d+(?:\\.\\d{0,2})?|\\.\\d{0,2})?)
Replace $1 替换$1

Expanded 展开式

  ^ 
 (                             # (1 start)
      [-+]? 
      (?:
           \d+ 
           (?:
                \. \d{0,2} 
           )?
        |  
           \. \d{0,2} 
      )?
 )                             # (1 end)

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

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