Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua string.gsub with Multiple Patterns

I am working on renaming the Movie titles that has unwanted letters. The string.gsub can replace a string with "" nil value but I have around 200 string patterns that need to be replaces with "".

Right now I have to string.gsub for every pattern. I was thinking is there is a way to put all the string patterns in to single string.gsub line. I have searched around the web for the solution but still didn't got anything.

The movie title is like this B.A.Pass 2013 Hindi 720p DvDRip CROPPED AAC x264 RickyKT and I want to remove the extra characters like 2013, Hindi, 720p, DvDRip, CROPPED, AAC, x264, RickyKT.

like image 988
Prakash.DTI Avatar asked Aug 13 '14 07:08

Prakash.DTI


People also ask

What does GSUB do in Lua?

gsub() function has three arguments, the first is the subject string, in which we are trying to replace a substring to another substring, the second argument is the pattern that we want to replace in the given string, and the third argument is the string from which we want to replace the pattern.

What does string GSUB return?

gsub (s, pattern, repl [, n]) Returns a copy of s in which all (or the first n , if given) occurrences of the pattern have been replaced by a replacement string specified by repl , which can be a string, a table, or a function.

What is %w Lua?

Valid in Lua, where %w is (almost) the equivalent of \w in other languages. ^[%w-.]+$ means match a string that is entirely composed of alphanumeric characters (letters and digits), dashes or dots.

How do I match a string in Lua?

> = string. match("foo 123 bar", '%d%d%d') -- %d matches a digit 123 > = string. match("text with an Uppercase letter", '%u') -- %u matches an uppercase letter U. Making the letter after the % uppercase inverts the class, so %D will match all non-digit characters.


1 Answers

You can pass to string.gsub a table as the third argument like this:

local movie = "B.A.Pass 2013 Hindi 720p DvDRip CROPPED AAC x264 RickyKT"
movie = movie:gsub("%S+", {["2013"] = "", ["Hindi"] = "", ["720p"] = "", 
                       ["DvDRip"] = "", ["CROPPED"] = "", ["AAC"] = "", 
                       ["x264"] = "", ["RickyKT"] = ""})

print(movie)
like image 106
Yu Hao Avatar answered Sep 22 '22 15:09

Yu Hao