dongyou6795 2015-12-23 16:49
浏览 291
已采纳

解析文本文件以匹配字符串并提取值(在Golang中)

I am scratching my head around a need that seems to be potentially common but I couldn't locate any example on the web.

I have a file like this:

  answer VNET_1_DHCP yes
  answer VNET_1_DHCP_CFG_HASH 4CF2C196E368CE83B9D1895C5E05301CDFDEBCA0  
  answer VNET_1_HOSTONLY_NETMASK 255.255.255.0
  answer VNET_1_HOSTONLY_SUBNET 192.168.224.0
  answer VNET_1_VIRTUAL_ADAPTER yes
  answer VNET_8_DHCP yes
  answer VNET_8_DHCP_CFG_HASH D326C0BC7FF6C38C57AF341F9075E576C175B250
  answer VNET_8_HOSTONLY_NETMASK 255.255.255.0
  answer VNET_8_HOSTONLY_SUBNET 172.16.102.0
  answer VNET_8_NAT yes
  answer VNET_8_VIRTUAL_ADAPTER yes

I need to extract the VNET number of a specific subnet (192.168.224.0). VNET numbers could vary (and the subnet could, in theory, not even exist). So I need to match if the subnet exists, and if exists extract the network number (1 in this example).

I found it to be SUPER easy to implement this in BASH:

 if grep -q 192.168.224.0 ./networking; then
      echo "The ${VMNET_SUBNET} network already exists"
      NETWORK_NUMBER=$(grep ${VMNET_SUBNET} ./networking | cut -d'_' -f 2)
      echo NETWORK_NUMBER  
 else <do something to create it.....> 

I am trying to find the easiest way to implement this using Go.

Thanks.

  • 写回答

3条回答 默认 最新

  • dqgo99177 2015-12-23 17:05
    关注

    You can use a regular expression:

    re := regexp.MustCompile(`.*VNET_(\d+)_.*192.168.224.0`)
    matches := re.FindStringSubmatch(text)
    fmt.Println(matches[1])
    

    Playground: http://play.golang.org/p/NQlA2BObtU.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 咨询一下有关于王者荣耀赢藏战绩
  • ¥100 求购一套带接口实现实习自动签到打卡
  • ¥50 MacOS 使用虚拟机安装k8s
  • ¥500 亚马逊 COOKIE我如何才能实现 登录一个亚马逊账户 下发新 COOKIE ..我使用下发新COOKIE 导入ADS 指纹浏览器登录,我把账户密码 修改过后,原来下发新COOKIE 不会失效的方式
  • ¥20 玩游戏gpu和cpu利用率特别低,玩游戏卡顿
  • ¥25 oracle中的正则匹配
  • ¥15 关于#vscode#的问题:把软件卸载不会再出现蓝屏
  • ¥15 vimplus出现的错误
  • ¥15 usb无线网卡转typec口
  • ¥30 怎么使用AVL fire ESE软件自带的优化模式来优化设计Soot和NOx?