How to Use String.Find() With Hyphens?

So I made a similar post to this before because there are certain characters that you can’t use string.find() normally on. A hyphen is one of these characters.

I know that if I wanted to find it manually I would have to use an escape like:

local str = "oof\-ed"
local bigstring = "That guy got oof-ed" 
local st,en = string.find(bigstring, str)

But how would I be able to automatically detect if a string variable had a hyphen in it? So I could properly use string.find without knowing what str is? Because the issue is this doesn’t work at all:

local str = "oof-ed"
local bigstring = "That guy got oof-ed" 
local st,en = string.find(bigstring, str)
1 Like
local str = "oof%-ed"

I think this should work.

You’re not getting what I’m asking. I don’t know what str, it’s just a variable. So how can I call

string.find(bigstring, str)

and have it return a result when str has a hyphen in it?

string.find(bigstring, str, 1, true)

Still not entirely sure if this is what you’re asking?

2 Likes

Yes actually I just found that on my own too, thanks for the help that’s what I was looking for.

1 Like

You can use a hyphen in string.find, but do to it being a magic character, it must be escaped to match the actual character -. (It’s used as a quantifier, so {.-} will match a {, as few characters as possible, and then a })

If you don’t want the pattern matching, use the fourth argument.