简体   繁体   English

正则表达式否定接受带有前导零的数字

[英]Regex to negate accepting numbers with leading zeros

So below is the directive i am using to ensure the input is purely number from 0-9.所以下面是我用来确保输入纯粹是 0-9 的数字的指令。

import { Directive, HostListener, ElementRef } from "@angular/core";

@Directive({
  selector: "[numbersOnly]",
})
export class OnlynumberDirective {
  constructor(private _el: ElementRef) {}

  @HostListener("input", ["$event"]) onInputChange(event) {
    const initalValue = this._el.nativeElement.value;

    this._el.nativeElement.value = initalValue.replace(/[^0-9]*/g, "");
    if (initalValue !== this._el.nativeElement.value) {
      event.stopPropagation();
    }
  }
}

At the moment, it only allows numbers (no special characters) as it performs data cleanup and replaces the non-numeric chars with empty space.目前,它只允许数字(无特殊字符),因为它执行数据清理并用空格替换非数字字符。 Now i want to change my regex to not allow numbers containing leading zeros.现在我想更改我的正则表达式以不允许包含前导零的数字。 It can have zeros but not just in the start.它可以有零,但不仅仅是在开始时。

  1. 90123 -> Accepted 90123 -> 接受
  2. 100001 -> Accepted 100001 -> 接受
  3. 01223 -> Not accepted 01223 -> 不接受
  4. 0 -> Not accepted 0 -> 不接受

Please suggest me a regex that can work with this.请建议我一个可以使用这个的正则表达式。

You can use /\D|^0+/g for data cleanup like so:您可以使用/\D|^0+/g进行数据清理,如下所示:

initalValue.replace(/\D|^0+/g, "");

In English it says:在英语中它说:

Find anything not a digit ( \D ) or ( | ) leading zeros ( ^0+ ) and replace it with nothing查找任何不是数字 ( \D ) 或 ( | ) 前导零 ( ^0+ ) 的内容并将其替换为空

 console.log('90123'.replace(/\D|^0+/g, "")); console.log('100001'.replace(/\D|^0+/g, "")); console.log('01223'.replace(/\D|^0+/g, "")); console.log('001223'.replace(/\D|^0+/g, "")); console.log('0'.replace(/\D|^0+/g, ""));

Or you can use或者你可以使用

/^[^1-9]+/g

Leading ^ character that is not ^ number 1 to 9不是^数字 1 到 9 的前导^字符

 console.log('00090123'.replace(/^[^1-9]+/g, "")); console.log('100001'.replace(/^[^1-9]+/g, "")); console.log('01223'.replace(/^[^1-9]+/g, "")); console.log('001223'.replace(/^[^1-9]+/g, "")); console.log('0'.replace(/^[^1-9]+/g, ""));

you can try this你可以试试这个

 var str="90123 " var str1="100001" var str3="01223" pattern=/^0|D{1}\d+/g console.log(str.replace(pattern,"")) console.log(str1.replace(pattern,"")) console.log(str3.replace(pattern,""))

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

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