Search code examples
stringlualua-patterns

Extracting an IP address from a particular string in Lua


I want to extract a particular value from a string . This is my string

iptables -t nat -A PREROUTING -p tcp -m tcp --dport 666 -j DNAT --to-destination 192.168.19.55

How can i extract 192.168.19.55 ip address from this string using string.match in lua ?

I done with local ip = s:match("--to-destination (%d+.%d+.%d+.%d+)")) but i didn't get the value 192.168.19.55 . I am getting empty value .

Any mistake in this ? Any suggestions ?


Solution

  • Use

    local s = "iptables -t nat -A PREROUTING -p tcp -m tcp --dport 666 -j DNAT --to-destination 192.168.19.55"
    ip = s:match("%-%-to%-destination (%d+%.%d+%.%d+%.%d+)")
    print(ip)
    -- 192.168.19.55
    

    See the online Lua demo.

    Note that - is a lazy quantifier in Lua patterns, and thus must be escaped. Also, a . matches any char, so you need to escape it, too, to match a literal dot.

    See more at Lua patterns Web page.