javascript - 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 ....
解决方案
你可以试试:
(?:\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);
推荐阅读
- python - 解析所需文件的列表python
- flutter - 输入'列表
' 不是类型 'List 的子类型 ' 在类型转换中 - autodesk-forge - 查看器扩展网络呼叫超时
- oauth - 使用哪个 O Auth 流程来验证在前端获得的第 3 方访问令牌
- mysql - 重新排列列的顺序?
- javascript - 无法读取未定义的属性“天空”
- java - 如何比较 Intellij 中 2 个不同存储库的相同文件?
- python - 为什么在解析之前循环数据框中的列会导致索引错误,Python 3.6+?
- python - 使用日期时间列切片数据框(Python - Pandas)
- angular - 将 Angular 材质添加到 Nx 工作区