PDA

View Full Version : Regular Expression question - please help!


shervin
04-07-2007, 03:20 PM
Im trying to replace a list of words with some other word, like this:

--------------------------------------------------------------------------------------

input = "word1 word2 word3 word4 word5";
pattern = "(word2|word4)";
replacestring = "someword";

string.gsub( input, pattern, replacestring);

--------------------------------------------------------------------------------------

but it doesn't work. it works in other languages though.
It matches the whole string all the time.

I want the result to be: "word1 someword word3 someword word5"

Any help would be useful, I would like to do this with regex instead of search & replace.

Duugu
04-07-2007, 04:43 PM
imho the only way to do this is to iterate on the string:

result = ""
s = "word1 word2 word3 word4 word5"
pattern = "word2 word4"
replacestring = "someword"
for w in string.gsub(s, "%w+") do
if string.find(pattern, w) then
result = result..replacestring.." "
else
result = result..w.." "
end
end
DEFAULT_CHAT_FRAME:AddMessage(result)

Telic
05-07-2007, 10:53 AM
If you put the list of words you want to replace in to a test_array, and define a simple little function like SubMyWord, then something like the following should work :


input = "word1 word2 word3 word4 word5";
test_array = {"word2", "word4"};
replacestring = "someword";

function SubMyWord(wrd)
if ( test_array[wrd] ) then
return replacestring;
else
return wrd;
end
end

output = string.gsub(input, "(%w+)", SubMyWord)


The ability of the third gsub argument to be a function can be very useful, so I hope the above works for you :smiley: