In Lua, to check if matched text is found in a string, you can primarily use the string.find function from the standard library. This function searches a specified pattern within a string. If a match is found, it returns the start and end indices of the matched substring; otherwise, it returns nil.
For example, here's how to use the string.find function:
lua-- Define a string local str = "Hello, welcome to the world of Lua." -- Text to search for local pattern = "welcome" -- Use string.find to search local start_pos, end_pos = string.find(str, pattern) if start_pos then print("Found matched text: '" .. pattern .. "' at position " .. start_pos .. " to " .. end_pos) else print("No matched text found in the string: '" .. pattern .. "'") end
In this example, we first define a string str and the text we want to search for, pattern. Then we call the string.find function to perform the search. string.find returns the start and end positions of the matched text, and we use this return value to determine if a match was found.
Additionally, the string.find function can handle pattern matching, allowing for more complex text searches using Lua's pattern matching syntax. For instance:
lualocal str = "我有100个苹果,你有20个橘子。" local pattern = "(%d+)个橘子" local match = string.match(str, pattern) if match then print("Found number: " .. match) else print("No matching number found.") end
In this example, string.match is used to directly extract the matched part. (%d+) is a capture group that matches one or more digits. This approach allows the function not only to check for a match but also to directly extract the matched information, which is very convenient.