简体   繁体   English

使用 replace 删除正则表达式匹配中不存在的字符

[英]use replace to remove chars not existing in a regex match

I'am trying to allow following pattern for a single html input box with javascript regex我正在尝试允许使用 javascript 正则表达式的单个 html 输入框的以下模式

  • -int (aka any minus number so long it not followed by a zero and is in the first position) -int(又名任何负数,只要它后面没有零并且位于第一个位置)
  • 0 (a single zero is allowed) 0(允许单个零)
  • int (is allowed)整数(允许)

I use this function the remove anything that doesn't match it我使用这个 function 删除任何不匹配的东西

    $('.dointcheck').live('keyup',
        function () {
            $(this).val($(this).val().replace((/^((?!:([1-9-]?[0-9])).)/g), ''));
            if ($(this).val().length == 0) {
                $(this).val(0);
            }
        }); 

which doesn't work.这是行不通的。 Other examples is:其他例子是:

  1. /[^-0-9]/g it removes any non valid chars but doesnt check if the minus is the beginning and is followed by a zero. /[^-0-9]/g它会删除任何无效字符,但不会检查减号是否为开头且后跟零。 It allows minus everywhere in the string它允许在字符串中的任何地方减号
  2. (/^((?:?([1-9-].[0-9])).)/g Don't allow none. (/^((?:?([1-9-].[0-9])).)/g一个都不允许。
  3. [^1-9-]?[^0-9] * Allow all... [^1-9-]?[^0-9] * 允许所有...

I think I'am missing something.. Any suggestions would be most appreciated..我想我遗漏了一些东西..任何建议将不胜感激..

I changed your regexp and made it a bit more modular and it worked fine.我更改了您的正则表达式并使其更加模块化并且运行良好。

function toValidNumber(int) {
  return (/^\s*[+-]?(\d+|\d*\.\d+|\d+\.\d*)([Ee][+-]?\d+)?\s*$/).test(int) ? int : 0;
}

$('.dointcheck').live('keyup',
  function () {
    $(this).val(toValidNumber($(this).val()));
  }); 

Orginal RegEXP in Stackoverflow Stackoverflow 中的原始 RegEXP

You may try this regex你可以试试这个正则表达式

^(0).*|^(-?)([1-9]\d*)?.*|^.*

and replace it with $1$2$3 after input输入后替换为$1$2$3

 document.querySelector('input').addEventListener('input', ({ target }) => target.value = target.value.replace(/^(0).*|^(-)?([1-9]\d*)?.*|^.*/g, '$1$2$3'));
 <input />

It has three tests:它有三个测试:

^(0).*               // if it starts with 0, discard everything after it
^(-)?([1-9]\d*)?.*   // otherwise it can only starts with a -, or any number that is not a 0. Then followed by other digits, then discard everything after it
^.*                  // if previous rules are not matched, discard everything

In short:简而言之:

  • generally only - , 0-9 are allowed.通常只允许- , 0-9
  • if you type a 0 first, nothing will be allowed after.如果您先输入0 ,则之后将不允许输入任何内容。
  • if you type a 1-9 first, only numbers are allowed after.如果您先输入1-9 ,则后面只允许输入数字。
  • if you type a - first, only 1-9 is allowed next, then any digit is allowed after.如果您先输入- ,则接下来只允许输入1-9 ,然后输入任何数字。

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

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