1
votes

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:

  • "player.position"
  • "player.style"
  • "target.width"
  • "enemy.height"

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.

1

1 Answers

1
votes

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