用于强制填充字符串字段的正则表达式

问题描述 投票:-2回答:2

我需要找到一种方法来指导用户填写字符串字段。我需要强制用户以这种方式填充字段:

IP ADRESS (SPACE) PORT (end)

IP ADRESS (SPACE) PORT (end)

例如:

123.45.70.2 8080

143.23.10.10 433

我需要具有IP地址和相关端口的列表。

我在RegEx上阅读了一些内容,但是找不到解决方法。

我要控制的字段是服务目录项的多行文本变量。

有人可以帮我吗?

感谢。

javascript regex servicenow
2个回答
1
投票

您可以使用下面的代码使用javascript提取给定字符串中的所有IP地址:

function findAll(regexPattern, sourceString) {
    let output = []
    let match
    // make sure the pattern has the global flag
    let regexPatternWithGlobal = RegExp(regexPattern,"g")
    while (match = regexPatternWithGlobal.exec(sourceString)) {
        // get rid of the string copy
        delete match.input
        // store the match data
        output.push(match[0].replace(":", " "))
    } 
    return output
}


var str = "123.23.255.123:1233 128.9.88.77:1233"; 
var ipAddress = findAll("(([0-1]?[0-9]?[0-9]|[2]?[0-5][0-5])\.){3}([0-1]?[0-9][0-9]|[2]?[0-5][0-5])\:[0-9]{4}", str);

RegExp(str, "g")
console.log(ipAddress)

以上代码的输出将是

[ '123.23.255.123 1233', '128.9.88.77 1233' ]

0
投票

可以在此处使用正则表达式,但对于边缘情况您必须非常小心。

此示例解决了多行字符串的问题,该字符串应仅包含IPv4地址,后接空格。”>

例如

123.45.70.2 8080
143.23.10.10 433

和JS代码示例

var textInput= `
123.45.70.2 8080
143.23.10.10 433
`.trim();

var isValid = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3} [1-9][0-9]*$/mg.test(textInput);
console.log(isValid);
© www.soinside.com 2019 - 2024. All rights reserved.