Mayron
Mayron

Reputation: 2394

Lua string.match - matching on optional words in a string

I need a Lua pattern to match when 1 of 3 exact words are found at the start of a string but I can only find solutions online to show how to match against the type of characters, i.e. does it begin with a number or punctuation character.

For example, the following strings should match the pattern:

We can assume the first word will either be "player", "target" or "enemy" so can I create a pattern that groups them together and matches if only 1 of them is found in the string? The rest of the text after the "." can be anything.

I came up with this pattern but there are many problems with it:

local pattern = "[player target enemy]*%..+";

The first part can match any sequence of characters contained between the square brackets, so for example "bannana_target_apple.position" used with this pattern would return "apple.position" because "a", "p", "l", and "e" are found between the square brackets in the pattern.

Thank you for any help you can provide.

Upvotes: 1

Views: 972

Answers (1)

Egor   Skriptunoff
Egor Skriptunoff

Reputation: 974

Lua pattern to match when 1 of 3 exact words are found at the start of a string:

if ({player=0, target=0, enemy=0})[your_string:match"^(%w+)%."] then 
   ... 
end

Upvotes: 1

Related Questions