What is the alternation operator in Lua patterns?
Asked Answered
P

3

10

In regex, | is used for alternation. What is the corresponding character in Lua patterns?

Phytogeography answered 3/5, 2012 at 19:48 Comment(1)
See also Lua string.match uses irregular regular expressions?Scrivner
S
20

First, note that Lua patterns are not regular expressions; they are their own simpler matching language (with different benefits and drawbacks).

Per the specification I've linked to above, and per this answer, there is no alternation operator in a Lua pattern. To get this functionality you'll need to use a more powerful Lua construct (like LPEG or a Lua Regex Library).

Scrivner answered 3/5, 2012 at 19:56 Comment(3)
I will complement this perfectly good answer by saying that sometimes you can get away with not using LPEG or Lua Regex - a plain ´or´ might do the trick: if s:match(a) or s:match(b) then ...Hawserlaid
often you can also get away with a more general match and switch on the result...: local word = s:match("%w+") if word =="foo" or word == "bar" then.... else ....... endKaela
I came to this question from the perspective of Arduino Regexp (which is based on Lua patterns). I was hoping this answer would include a work-around that I could port.Adi
K
3

Lua does not have alternations in patterns you cannot use (test1|test2). You can only choose between multiple characters like [abcd] will match a, b, c or d.

Karat answered 19/2, 2020 at 13:1 Comment(0)
H
-5

Another workaround is: Instead of:

apple|orange

Write:

[ao][pr][pa][ln][eg]

Explanation: match alternate letters from each word. voila!

Heterochromous answered 8/6, 2017 at 1:25 Comment(1)
That would match arplg as well.Sailing

© 2022 - 2024 — McMap. All rights reserved.