3

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 ?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
vkp_stack
  • 157
  • 1
  • 16
  • You need to use `%-` to escape `-`, which is a magic character in Lua patterns. – lhf Jul 26 '17 at 14:32

2 Answers2

4

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    Note that if you are sure it is always IP that comes from `destination`, you may also use [`s:match("%-%-to%-destination ([%d.]+)")`](https://ideone.com/pTzGrq). A `.` inside `[...]` does not have to be escaped, and `[%d.]+` matches one or more digits or dots. – Wiktor Stribiżew Jul 26 '17 at 14:08
3

This also works:

ip = s:match("destination%s+(%S+)")

It extracts the next word after destination, a word being a run of nonwhitespace characters.

lhf
  • 70,581
  • 9
  • 108
  • 149
  • Yes, it would work for IPv6 too. But probably it would be better to restrict number of available characters (for example, `()-"` should not be allowed) – Egor Skriptunoff Jul 26 '17 at 18:29