Matching lua: delimiters

I'm trying to parse a string like: &1 first &2 second &4 fourth \\ , and build a table from it

 t = {1=first, 2=second, 4=fourth} 

I am not very good at regular expression, so my naive attempt (excluding \\ and parts of the table at the moment) was

 local s = [[&1 first &2 second &4 fourth \\]] for k,v in string.gmatch(s, "&(%d+)(.-)&") do print("k = "..k..", v = "..v) end 

which gives only the first captured pair when I expected to see two captured pairs. I did some reading and found the lpeg library, but that was not familiar to me. Need lpeg ? Can someone explain my mistake?

+4
source share
2 answers
  • &(%d+)(.-)& matches &1 first &
  • Leave 2 second &4 fourth \\ to match
  • Your template does not match other elements.
+2
source

If you know the values ​​are one word, this should work:

 string.gmatch(s, "&(%d+)%s+([^%s&]+)") 

Take "&" followed by 1 or more digits (captured), followed by one or more spaces, and then one or more non-spatial, non-amp; characters (removed).

+1
source

Source: https://habr.com/ru/post/1486114/


All Articles