String patterns "-"

string.match("Hello", "%a-")

What does the “-” magic element do in string.match()?


I know what all the elements except the minus sign do. Please explain as clearly as possible. I dont get it from the official documentation.

1 Like

Quote from the docs:

Although from what I can test in this case it seems to always return void or nil even after changing the input text to include numbers or symbols and a mix of them

Edit: @yo9sa I did more research and I found more info (It’s from standard Lua though so it might be different in Luau):

Programming in Lua : 20.2

Edit2: Also for anyone wondering, this is how I did my test:

local match = string.match

print(match("Hello", "%a-"))
print(match("1234", "%a-"))
print(match("`'#~", "%a-"))
print(match("Hello1234", "%a-"))
print(match("Hello`'#~", "%a-"))
print(match("`'#~Hello1234", "%a-"))
print(match("Hello 1234", "%a-"))
print(match("Hello `'#~", "%a-"))
print(match("`'#~ Hello 1234", "%a-"))
print(match("Hello Hello", "%a-"))
print(match("1234 1234", "%a-"))
print(match("`'#~ `'#~", "%a-"))
print(match("hello", "%a-"))
print(match("HELLO", "%a-"))
4 Likes

When I ran the test using %a- as a pattern it always resulted in a blank output but after trying [%a-] like you suggested the output is now like so interestingly enough:

1 Like

The behavior is different for string.match and string.format.

  • For string.format, it puts the specified “width” as a number of spaces to the right of the number:
print(string.format("%-15.i", "1"))

image

(15 spaces after 1 because we put 15 after the -.)

  • For string.match, the use case appears to be when you have multiple “sets”
print(string.match("abc12345xyz", "[%a-][%d]"))

, thus, for the match to complete, it needs to pull atleast 1 character from the set that uses the -, because otherwise, it’s poor friend [%d] will return no match:

image

Overall, it appears to not be that useful, so you probably don’t need to stress over it.

2 Likes