使用regex格式化IPv4字符串

时间:2018-03-18 19:31:13

标签: javascript regex

我正在编写一个Angular 5指令,用于在用户输入IPv4输入时对其进行验证。

目前它按预期工作,但它非常详细:

@OneToOne(mappedBy="person")
 private Employee employee;

如何在JavaScript中使用其他RegExp或字符串方法替换this.el.nativeElement.value = this.el.nativeElement.value .replace(/^\D+/, '') // Remove any non-digit from position 0 .replace(/[^\d\.]+/, '') // Remove any non-digit, non dot from string .replace(/\.{2,}/, '.') // Force sequences of dots into one single dot .split('.').map(seq => seq.substring(0, 3)) // Limit to {1-3} digits per group .slice(0, 4) // Limit to 4 groups of digits .join('.') // Turn back into string and give dots back - split - map - slice序列?

1 个答案:

答案 0 :(得分:0)

您的请求有点复杂,请说容错。所以给定     " asdf1.2.3.aaa ... 4afd" 你应该得到:" 1.2.3.4"。

由于第二次替换,第一次替换(.replace(/ ^ \ D + /,''))似乎是多余的。整个表达可能是

var original = "asdf1.2.3.aaa...4afd";
var formatted = original.replace(/[^\d.]/g, "")
            .replace(/^\.*(\d+)\.+(\d+)\.+(\d+)\.+(\d+)[^\d]?.*$/g, "$1.$2.$3.$4");

请注意,这会给非IPv4字符串带来不同的结果。喜欢" 1.2.3"所以你可能想把这段代码测试为:

        var a = "asdf1.2.3.aaa...4afd";
        var a = "asdf2.3.aaa...4.5.6af.7d";
        var a = "1.2.3.4";
        var a = "1.2.3";
        var a = "1.2";
        var b = a.replace(/[^\d.]/g, "");
        var c = b.replace(/^\.*(\d+)\.+(\d+)\.+(\d+)\.+(\d+)[^\d]?.*$/g, "$1.$2.$3.$4");
        console.log(a + "  " + b + "  " + c);