英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论