如何在Lua中使用grep查找字符串文本?

huangapple go评论60阅读模式
英文:

How to grep string text in lua?

问题

local str = [[hello1 : hello01
hello2 : hello02
hello3 : hello03]]

function some_func(input_str, target_text)
  local result = ""
  for line in input_str:gmatch("[^\n]+") do
    if line:find(target_text) then
      result = result .. line .. "\n"
    end
  end
  return result
end

print(some_func(str, "hello2"))
英文:

How can I get all the lines from string text that contain specific text?
for example:

local str = [[hello1 : hello01
hello2 : hello02
hello3 : hello03]]

print(some_func(str, "hello2"))

So I want to get in this case:

hello2 : hello02

I tried to use print(string.find(str, "hello2")) but i get only the first index and end index of hello2 in this string (18 23).

we can think about it like a grep about string text (in bash, but i trying to do it in lua:

echo "hello1 : hello01
hello2 : hello02
hello3 : hello03" | grep "hello2"

答案1

得分: 1

你可以使用以下函数:

function get_lines_with_text(inputstr, search)
    local t={}
    for str in string.gmatch(inputstr, "[^\n]*"..search.."[^\n]*") do
        table.insert(t, str)
    end
    return t
end

查看Lua演示

这是使用你的字符串进行的测试:

local str = [[hello1 : hello01
hello2 : hello02
hello3 : hello03]]

for _, line in pairs(get_lines_with_text(str, "hello2")) do
    print(line)
end

输出结果为 hello2 : hello02

英文:

You can use the following function:

function get_lines_with_text(inputstr, search)
    local t={}
    for str in string.gmatch(inputstr, "[^\n]*"..search.."[^\n]*") do
        table.insert(t, str)
    end
    return t
end

See the Lua demo.

Here is a test using your string:

local str = [[hello1 : hello01
hello2 : hello02
hello3 : hello03]]

for _, line in pairs(get_lines_with_text(str, "hello2")) do
	print(line)
end

that outputs hello2 : hello02.

huangapple
  • 本文由 发表于 2023年1月9日 19:27:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75056615.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定