问题描述:

Please find my code below.

str = "1791 (AR6K Async) S 2 0 0 0 -1 2129984 0 0 0 0 0 113 0 0 20 0 1 0 2370 0 0 4294967295 0 0 0 0 0 0 0 2147483647 0 3221520956 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0"

for val in str:gmatch("%S+") do

print(val)

end

Output:

1791

(AR6K

Async)

S

2

0

0

0

-1

....

But I am expecting the output like,

1791

(AR6K Async)

S

2

0

0

-1

...

Can anyone please help me how to get the values in bracket as a single value instead getting separate values.

网友答案:
str = "1791 (AR6K Async) S 2 0 0 0 -1 2129984 0 0 0 0 0 113 0 0 20 0 1 0 2370 0 0 4294967295 0 0 0 0 0 0 0 2147483647 0 3221520956 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0"

for val in str:gsub("%S+","\0%0\0")
              :gsub("%b()", function(s) return s:gsub("%z","") end)
              :gmatch("%z(.-)%z") do
   print(val)
end

Explanation:
1. Surround all spaceless substrings with "zero marks"
(add one binary-zero-character at the beginning and one at the end)
2. Remove "zero marks" from inside parentheses
3. Display all surrounded parts

网友答案:

It may not be possible to use a single lua pattern alone to do this.

However it can be easy to roll your own parsing / splitting of the string or just extend your code a bit to concatenate the parts from a part that starts with ( to the part that ends with )

Here is a small example

str = "1791 (AR6K Async) S 2 0 0 0 -1 2129984 0 0 0 0 0 113 0 0 20 0 1 0 2370 0 0 4294967295 0 0 0 0 0 0 0 2147483647 0 3221520956 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0"

local temp
for val in str:gmatch("%S+") do
  if temp then
    if val:sub(#val, #val) == ")" then
      print(temp.." "..val)
      temp = nil
    else
      temp = temp.." "..val
    end
  elseif val:sub(1,1) == "(" then
    temp = val
  else
    print(val)
  end
end

This code behaves exactly like your own, except that when it encounters a substring that starts with an opening bracket, it will save it to temp variable. Then it will concatenate new values to temp until a substring with the closing bracket at the end of it is encountered. At that point the whole string saved to temp will be printed and temp is set to nil and the loop is continued normally.

So there is just a special case coded for when a string with brackets comes by.

This may not be the most efficient implementation, but it works. Also this assumes that the separators are spaces, since when the strings are concatenated to temp variable, they will be concatenated with an ordinary space. This does not handle nested brackets. This was just a quick demonstration of the idea however so I believe you can fix these shortcomings on your own as you need to if you use it.

相关阅读:
Top