Search code examples
regextclcisco

tcl regex with variables


I need to verify what ip address is announce the default route:

set command [ exec "show ip route" ]

the ouput:

Codes: L - local, C - connected, S - static, R - RIP, M - mobile, B - BGP
       D - EIGRP, EX - EIGRP external, O - OSPF, IA - OSPF inter area
       N1 - OSPF NSSA external type 1, N2 - OSPF NSSA external type 2
       E1 - OSPF external type 1, E2 - OSPF external type 2
       i - IS-IS, su - IS-IS summary, L1 - IS-IS level-1, L2 - IS-IS level-2
       ia - IS-IS inter area, * - candidate default, U - per-user static route
       o - ODR, P - periodic downloaded static route, H - NHRP, l - LISP
       + - replicated route, % - next hop override

Gateway of last resort is 10.17.1.252 to network 0.0.0.0

B*    0.0.0.0/0 [200/0] via 10.17.1.252, 01:16:22
      10.0.0.0/8 is variably subnetted, 2 subnets, 2 masks
C        10.17.1.0/24 is directly connected, FastEthernet1/0
L        10.17.1.253/32 is directly connected, FastEthernet1/0
      172.22.0.0/32 is subnetted, 1 subnets
C        172.22.12.250 is directly connected, Loopback1
      172.26.0.0/16 is variably subnetted, 3 subnets, 2 masks
B        172.26.69.64/30 [200/0] via 10.17.1.252, 01:16:33
C        172.26.70.64/30 is directly connected, FastEthernet0/0
L        172.26.70.66/32 is directly connected, FastEthernet0/0

I need to find this: "0.0.0.0/0 [200/0] via 10.17.1.252", but this address: 10.17.1.252 can change, how I can put a variable in a regex ?

set routes [ regexp {(0.0.0.0\/0 \[200\/0\] via $bgp_neighbor)} $command match default_route ]

Solution

  • A regular expression isn't the best choice for this.

    string first [format {0.0.0.0/0 [200/0] via %s} $bgp_neighbor] $command 
    

    When searching for a zero variance pattern, string first is the closest match. Building the pattern with format minimizes the amount of escaping you need to do.

    In this case, there isn't much escaping needed anyway:

    string first "0.0.0.0/0 \[200/0] via $bgp_neighbor" $command
    

    Note that string first returns the position of the string if found, or -1 if not found.

    Documentation: string