首页 > 解决方案 > Javascript RegEx 需要替换字符串中的 IPv4 和端口号

问题描述

我有一个字符串,如:

  someCharactersHere andSomeMore  192.168.1.55 11211 typ someMorechars andYetMore 

我知道要替换的 IP 地址,但不知道端口号。我只知道它是一个整数,后跟“typ”。我正在寻找 JS 来替换任何这样的字符串

  someCharactersHere andSomeMore  192.168.3.34 20121 typ someMorechars andYetMore

因此,例如,这样做的函数将是:

        function newString(oldString, oldIp, newIp, newPort) {
          
            return oldString.replace(/regEx/, newIp + " " + newPort);
         
        }

有人可以帮助我使用正则表达式。IP 地址在字符串中只出现一次。整数端口号可能会出现在其他地方,但我要替换的端口号总是被左侧的单个空格包围,右侧的空格后跟“typ”。换句话说,要替换的目标是:

         .... oldIp oldPortNo typ ...

经过

         .... newIp newPortNo typ  ....

标签: javascriptregex

解决方案


你可以试试:

(?:\d{1,3}\.){3}\d{1,3} \d+(?= typ)

上述正则表达式的解释:

  • (?:\d{1,3}\.){3}- 表示匹配数字 1 到 3 次后跟.. 整组正好重复三遍。
  • \d{1,3}- 匹配数字 1 到 3 次。(用于 IP 的最后一部分)
  • \d+(?= typ)- 匹配后跟的数字 typ

图示

您可以在此处找到上述正则表达式的演示。

const regex = /(?:\d{1,3}\.){3}\d{1,3} \d+(?= typ)/g;
const str = `someCharactersHere andSomeMore  192.168.1.55 11211 typ someMorechars andYetMore
`;
const subst = `192.168.3.34 20121`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);


推荐阅读