Silly question, with what I'm sure has a simple answer

Posted by Rivius on Sat 11 Jun 2011 08:22 AM — 10 posts, 39,890 views.

#0
I'm trying to make a function to do a search, however, I encounter some troubles when I use hyphenated words.

For example string.find("hyphenated-word", "hyphenated-word") will give no result for me.
Australia Forum Administrator #1
Hyphen is one of the regexp "magic" symbols. Try putting a % in front of it.


print (string.find("hyphenated-word", "hyphenated%-word") ) --> 1 15

#2
Hrm, well I've tried dealing with the string by doing this:

local what = string.gsub("%1", "-", "%-")

and this

local what = string.gsub("%1", "%-", "%-")

But it doesn't seem to help.
Australia Forum Administrator #3
What are you trying to do here? Replace a hyphen by a hyphen?

You need the % in the regular expression, eg.


what = string.gsub("hyphenated-word", "%-", "(hello)")
print (what)  --> hyphenated(hello)word


However I should point out that if you are doing this in "send to script" that the % symbol has its own meaning (eg. %1, %2, and so on), so if using regular expressions you have to double them.

Eg (in send-to-script box):


what = string.gsub("hyphenated-word", "%%-", "(hello)")
print (what)  --> hyphenated(hello)word
#4
Ah yes. This is in a script file and is a search function to find room names in my map databased. Here's an excerpt of the code


if string.find(string.lower(map_table[a].name), string.lower(string.gsub(name, "%-", "%-")))


I was just trying to make it so that typing "cloud-formation" would still give a match. At the moment "cloud-" and "formation" do, but the other doesn't because of the regex problem I presume.

I'm sorry if I'm doing this entirely improperly :P
Australia Forum Administrator #5
If it's in a script file, then the syntax is OK but I don't know what you are trying to achieve. See this:


print ((string.gsub("hyphenated-word", "%-", "%-"))) --> hyphenated-word


You are replacing a hyphen with a hyphen. Why?
#6
Well, I have an alias where you enter a query and it searches the map table and returns matches. I encountered a problem where it wouldn't return matches if I typed a hyphenated word.
#7
I've figured out the problem. Strangely enough, I had to double escape the second hyphen.

string.lower(string.gsub(name, "%-", "%%-"))

But now it works. Thanks.
#8
You didn't double escape the hyphen, technically. You had to escape the percent sign in order to replace your hyphen with percent hyphen. In fact, %%%- would probably be more correct, escaping both symbols.
#9
Ah. That makes sense. I didn't even think of it that way.