Is there a way I can do a string pattern that will match "ab|cd"
so it matches for either "ab"
or "cd"
in the input string. I know you use something like "[ab]"
as a pattern and it will match for either "a"
or "b"
, but that only works for one letter stuff.
Note that my actual problem is a lot more complicated, but essentially I just need to know if there is an OR thing in Lua's string manipulation. I would actually want to put other patterns on each sides of the OR thing, and etc. But if it works with something like "hello|world"
and matches "hello, world!"
with both "hello"
and "world"
then it's great!
> = string. match("foo 123 bar", '%d%d%d') -- %d matches a digit 123 > = string. match("text with an Uppercase letter", '%u') -- %u matches an uppercase letter U. Making the letter after the % uppercase inverts the class, so %D will match all non-digit characters.
They all are based on patterns. Unlike several other scripting languages, Lua does not use POSIX regular expressions (regexp) for pattern matching.
Lua Pattern matching The `gmatch` function gmatch function will take an input string and a pattern. This pattern describes on what to actually get back. This function will return a function which is actually an iterator. The result of this iterator will match to the pattern.
gsub (s, pattern, repl [, n]) Returns a copy of s in which all (or the first n , if given) occurrences of the pattern have been replaced by a replacement string specified by repl , which can be a string, a table, or a function. gsub also returns, as its second value, the total number of matches that occurred.
Using logical operator with Lua patterns can solve most problems. For instance, for the regular expression [hello|world]%d+
, you can use
string.match(str, "hello%d+") or string.match(str, "world%d+")
The shortcut circuit of or
operator makes sure the string matches hello%d+
first, if if fails, then matches world%d+
Unfortunately Lua patterns are not regular expressions and are less powerful. In particular they don't support alternation (that vertical bar |
operator of Java or Perl regular expressions), which is what you want to do.
A simple workaround could be the following:
local function MatchAny( str, pattern_list )
for _, pattern in ipairs( pattern_list ) do
local w = string.match( str, pattern )
if w then return w end
end
end
s = "hello dolly!"
print( MatchAny( s, { "hello", "world", "%d+" } ) )
s = "cruel world!"
print( MatchAny( s, { "hello", "world", "%d+" } ) )
s = "hello world!"
print( MatchAny( s, { "hello", "world", "%d+" } ) )
s = "got 1000 bucks"
print( MatchAny( s, { "hello", "world", "%d+" } ) )
Output:
hello world hello 1000
The function MatchAny
will match its first argument (a string) against a list of Lua patterns and return the result of the first successful match.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With