简体   繁体   English

正则表达式在特定位置查找 IP 地址

[英]Regex to find IP Address in specific places

I have a yaml file which has IP Address as value with IP Address as key string.我有一个 yaml 文件,其中 IP 地址作为值,IP 地址作为键字符串。 Some times the the value maybe have multiple IP's on new line each.有时,该值可能在每个新行上都有多个 IP。 There are some other key:value pairs in this file whose value also has format like IP Address(xxxx) but as the key is not IP Address, I don't want to consider this to matched with IP Address regex.此文件中还有一些其他键值对,其值也具有类似 IP Address(xxxx) 的格式,但由于键不是 IP 地址,我不想考虑将其与 IP 地址正则表达式匹配。 Below is the sample yaml file in which I only want to find/match regex for IP Address only with key having IP Address and its values spanning over multi line.下面是示例 yaml 文件,我只想在其中查找/匹配 IP 地址的正则表达式,其中的键具有 IP 地址及其跨越多行的值。

test-key-1: some_value
test-key-2: 8.23.12.0
test-key-3: some_value
IP Address: 127.0.0.1
 127.0.0.1
 127.0.0.1
 127.0.0.1
test-key-4: test-value

As seen in above sample yaml file, test-key-2 has value which matches IP Address like format.如上面的样本 yaml 文件所示,test-key-2 的值匹配 IP 地址格式。 But I only want to match the IP Address and replace it with some test value.但我只想匹配 IP 地址并将其替换为一些测试值。 So the expected output should be as below where all IP Addresses are replaced with "some-replaced-value" but the test-key-2 is not changed even though its value matches IP Address like format.因此,预期的 output 应该如下所示,其中所有 IP 地址都替换为“some-replaced-value”,但 test-key-2 没有更改,即使它的值匹配 IP 地址格式。 While replacing the multi line IP Addresses with replacement text, the space at start of each line have to be retained as it is to have valid yaml format for multiline values.在用替换文本替换多行 IP 地址时,必须保留每行开头的空格,因为它具有有效的多行值 yaml 格式。

test-key-1: some_value
test-key-2: 8.23.12.0
test-key-3: some_value
IP Address: some-replaced-value
 some-replaced-value
 some-replaced-value
 some-replaced-value
test-key-4: test-value

Because you have some values which are valid IP addresses, to me, it seems like you need a YAML parser as a first round to first extract the keys-value pairs you're interested in (or exclude fields you are not) and then operate only on the results因为你有一些值是有效的 IP 地址,对我来说,你似乎需要一个 YAML 解析器作为第一轮来首先提取你感兴趣的键值对(或排除你不感兴趣的字段)然后操作只看结果

I am not a golang user, but this seems quite relevant Golang Map YAML Objects我不是 golang 用户,但这似乎很相关Golang Map YAML 对象

I suspect your program would then take a form like我怀疑你的程序会采取类似的形式

read yaml file

for each key-value pair
  if the key name is "IP Address"
    split the string
      replace each matching member (also error for non-matching?)

When transforming, it also may be better to use a dedicated IP parser as it probably provided by net than a regex, which may have extra features (such as trivially providing if the address is local or handling IPv6)转换时,最好使用专用的 IP 解析器,因为它可能由net提供,而不是正则表达式,后者可能具有额外的功能(例如如果地址是本地地址或处理 IPv6 则简单提供)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM