我正在尝试允许以下模式用于带有javascript regex 的单个html输入框
- -int(也就是任何负数,只要后面不跟零并且在第一个位置(
- 0(允许使用单个零(
- int(允许(
我使用这个功能删除任何不匹配的
$('.dointcheck').live('keyup',
function () {
$(this).val($(this).val().replace((/^((?!:([1-9-]?[0-9])).)/g), ''));
if ($(this).val().length == 0) {
$(this).val(0);
}
});
这不起作用。其他例子是:
- /[^0-9]/g它删除任何无效字符,但不检查减号是否是开头并后跟零。它允许在字符串中的任何位置使用减号
- (/^((?!:([1-9-]?[0-9]((。(/g不允许任何情况发生
- [^1-9-]?[^0-9]*允许所有
我想我错过了什么。。如有任何建议,不胜感激。。
您可以尝试此regex
^(0).*|^(-?)([1-9]d*)?.*|^.*
并在输入后将其替换为CCD_ 1
document.querySelector('input').addEventListener('input', ({ target }) => target.value = target.value.replace(/^(0).*|^(-)?([1-9]d*)?.*|^.*/g, '$1$2$3'));
<input />
它有三个测试:
^(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
简而言之:
- 通常只允许使用
-
、0-9
- 如果您先键入
0
,则之后将不允许任何内容 - 如果您先键入
1-9
,则后面只允许输入数字 - 如果您先键入
-
,接下来只允许键入1-9
,然后允许键入任何数字
我更改了您的regexp,使其更加模块化,并且运行良好。
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()));
});
堆栈溢出中的原始RegEXP