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

-2 javascript regex servicenow

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

IP ADRESS (SPACE) PORT (end)

IP ADRESS (SPACE) PORT (end)
Run Code Online (Sandbox Code Playgroud)

例如 :

123.45.70.2 8080

143.23.10.10 433
Run Code Online (Sandbox Code Playgroud)

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

I read something abuot RegEx , but i can't find a way to do it.

The field that i want to control is a Multiline Text variable of an item of Service Catalog.

Can anyone help me?

Thanks.

小智 5

您可以使用以下代码使用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)
Run Code Online (Sandbox Code Playgroud)

上面代码的输出将是

[ '123.23.255.123 1233', '128.9.88.77 1233' ]
Run Code Online (Sandbox Code Playgroud)