I'm still getting used to the concept of string patterns, and I've run into an issue regarding them. I'm trying to create a simple program that searches a string of text, for certain characters encapsulated in whatever the brackets may be. Here's an example:
local str = "Hello <<world>>, my <<name>> is <<John>>"
-- Match patterns with << ... >>
for noun in str:gmatch("<<.->>") do
print(noun)
end
This program will search through the string, matching everything that starts with <<
and ends with >>
, and everything in between. Good, that's what I want. However, let's say I wanted a different pattern that only got text between one of those tags instead of two (<
and >
instead of <<
and >>
). This is where I run into a problem:
-- Allow easy customization control over brackets
local matchNouns = {"<<", ">>"}
local matchOther = {"<", ">"}
local str = "<Hello> <<world>>, <my> <<name>> <is> <<John>>"
local function printOtherMatches(str)
-- Get opening and closing brackets
local open, close = unpack(matchOther)
-- Concatenate opening and closing brackets with
-- pattern for finding all characters in between them
for other in str:gmatch(open .. ".-" .. close) do
print(other)
end
end
printOtherMatches(str)
The program above will print everything between <
and >
(the matchOther
elements), however it also prints text captured with <<
and >>
as well. I only want the iterator to return patterns that explicitly match the opening and closing tags. So the output from above should print:
<<Hello>>
<<my>>
<<is>>
Instead of:
<<Hello>>
<world>
<<my>>
<name>
<<is>>
<<John>>
Basically, just like with markdown how you can use *
and **
for different formats, I'd like to create a string pattern for that in Lua. This was my attempt of emulating that kind of pattern sequence. If anyone has any ideas, or insight on how I could achieve this, I'd really appreciate it!
Aucun commentaire:
Enregistrer un commentaire