1

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 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Shame there is no built in regex for specifying ordered sequence of characters but I really like your solution, very clever. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.