首页 > 解决方案 > 强制填充字符串字段的正则表达式

问题描述

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

IP ADRESS (SPACE) PORT (end)

IP ADRESS (SPACE) PORT (end)

例如 :

123.45.70.2 8080

143.23.10.10 433

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

我读了一些关于 RegEx 的东西,但我找不到办法。

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

谁能帮我?

谢谢。

标签: javascriptregexservicenow

解决方案


您可以使用下面的代码使用 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' ]

推荐阅读