Quick mastery of Lua 5.3--string Library (2)

Source: Internet
Author: User

Q: The correlation function of pattern matching string?

A:

--[[String.find (s, pattern [, init [, plain]]) in the string"S"To find the first match pattern in a"pattern"Matches the substring, the function returns the starting and ending positions of the substring. If no return is found"nil"。 If the"pattern"Captures are defined, and the captures are returned in turn."Init"Can be specified from a string"S"Where to start the lookup, the default is1。"plain"Specifies whether to find the substring in the form of pattern matching, if"plain"For0, it will be based on"pattern"The literal meaning of the lookup substring, the default is non-0Value. ]]s ="Hello world! 123%a+ "Print(string. Find (S,"L"))- 3 3Print(string. Find (S,"L",6))- TenPrint(string. Find (S,"LLL",6))- NilPrint(string. Find (S,"%a+",6))- 7Print(string. Find (S,"%a+",6,0)) ----by using the third parameter, you can implement a substring that finds all matching "pattern" in a string. Localb =0LocalE =0 while true  Do    --Continue searching from the next position in the matching position. B, E =string. Find (S,"%a+", E +1)ifb = =Nil  Then  Break End    io. Write (string. Format ("%s,",string. Sub (s, B, E))- Hello, World, A,EndPrint()--[[string.gsub (s, pattern, repl [, N]) replaces the string "s" with a substring that matches the pattern "pattern" with "repl", and "n" replaces all matches by default if not specified.     The function returns the replaced string and the number of substitutions.     1, if "Repl" is a string (which can use the catch), then the string as a substitute.     Exception, "%0" represents the entire match.     2, if "Repl" is a "table", each match will use the first catch as a key to check this table.     If "REPL" is a function, the function is called with all catches as arguments at each match.     3. If no capture is set in "pattern", the entire pattern is captured by default. 4. If the query result of "table" or the return result of a function is a string or a number, it will be substituted. The result is "false" or "nil" when no substitution is made (that is, the original string before the match is preserved). ]]Print(string. Gsub ("Lua is cute","cute","Great"))-- Lua is great 1Print(string. Gsub ("All Lii","L","x"))-- Axx XII 3Print(string. Gsub ("Lua is great","Perl","Tcl"))-- Lua is great 0Print(string. Gsub ("Hello World","(%w+)","%1%1"))-- Hello Hello World 2Print(string. Gsub ("Hello World","%w+","%0%0",1))-- Hello Hello World 1Print(string. Gsub ("Hello World from Lua","(%w+)%s* (%w+)","%2%1"))-World Hello Lua from 2Print(string. Gsub ("home = $HOME, user = $USER","%$ (%w+)",OS. getenv))--Home =/home/roberto, user = Roberto 2Print(string. Gsub ("4+5 = $return 4+5$","%$(.-)%$", function (s)     return Load(s) ()End))- 4+5 = 9 1Localt = {Name="Lua", version="5.3"}Print(string. Gsub ("$name-$version. tar.gz","%$ (%w+)", T))- lua-5.3.tar.gz 2--[[String.match (s, pattern [, init]) returns the captured object specified by "pattern" in the string "s".     If no capture is set in pattern, the entire pattern is captured by default. The "Init" can specify where the string "s" begins to find (can be negative) and defaults to 1. ]]Print(string. Match ("home = $HOME, user = $USER","%$ (%w+)"))- HOMEPrint(string. Match ("home = $HOME, user = $USER","%$%w+"))- $HOMEPrint(string. Match ("home = $HOME, user = $USER","%$ (%w+)", the))- USER--[[String.gmatch (s, pattern) returns a "iterator".     Each call will continue to match "s" with the matching pattern "pattern" and return all catches. If no capture is set in pattern, the entire pattern is captured by default. ]]--iterates through all the words in the string. s ="Hello World from Lua" forWinch string. Gmatch (S,"%a+") Do  Print(W)End--Collect all "key-value" pairs in the string and deposit them in "table". t = {}s ="From=world, To=lua" forKvinch string. Gmatch (S,"(%w+) = (%w+)") DoT[k] = VEnd
Q: How to encode and decode "URL encoding"?

A: "URL encoding" is the encoding that the "HTTP" protocol uses to send the parameters in the URL. This encoding converts some special characters (such as ' = ', ' & ', ' + ') into the 16-binary form of the "%XX" encoding, and then converts the space character to ' + '. For example, to "a+b = c" encode a string as a "a%2Bb+%3D+c" . Finally, add a ' = ' between the parameter name and the argument value, and a ' & ' between the "name=value" pairs. For example, a parameter stored in a "table":
t = {name = "al", query = "a+b = c", q = "yes or no"}
will be encoded as,
name=al&query=a%2Bb+%3D+c&q=yes+or+no

Print("Encode:") function escape(s)     --Replace all special characters with the form "%xx". s =string. Gsub (S,"([&=+%c])", function (c)         return string. Format ("%%%02x",string. Byte (c))End) s =string. Gsub (S," ","+")--converts all whitespace characters to "+".     returnSEnd function encode(t)     Locals =""     forKvinch Pairs(t) Do        --"name" and "value" are separated by ' = '; "Name=value" pairs are separated by ' & '. s = S.."&".. Escape (k):"=".. Escape (v)End    return string. Sub (S,2)--delete the first redundant ' & '. Endt = {name ="Al", query ="a+b = C", q="Yes or no"}s = Encode (t)Print(s)- Name=al&query=a%2bb+%3d+c&q=yes+or+noPrint()Print("Decode:") function unescape (s) s =string. Gsub (S,"+"," ")--Converts all "+" to spaces.     --Converts all "%XX" to ASCII characters. s =string. Gsub (S,"percent (%x%x)", function (h)         return string. Char (Tonumber(H, -))--16 decimal to Integer, Integer to ASCII.     End)returnSEnd function decode(table, s)     -Identify each "name-value" pair and further identify "name" and "value".     string. Gsub (S,([^&=]+) = ([^&=]+) ], function(name, value)         Table[Unescape (name)] = unescape (value)End)EndT1 = {}decode (t1, s) forI, Vinch Pairs(t1) Do Print(I, V)End--[[result:encode:name=al&query=a%2bb+%3d+c&q=yes+or+no decode:name al Query A+b = C Q Yes or No]]
Q: Some other practical applications?

A:

_, Count =string. gsub (STR," "," ")--Calculates the number of empty cells in a string. _, Count =string. gsub (STR,"([Aeiouaeiou])","%1")--Calculates the number of vowels in a string. '% (%s*%) '    --Match empty brackets (no content in parentheses or only spaces). ' [_%a][_%w]* '    --Match all the variable names in Lua. ' [+-]?%d+ '    --matches all values. if string. Find (S,"^%d") Then...End    --whether the string begins with a number. if string. Find (S,"^[+-]?%d+$") Then...End    --whether the string is an integer. string. gsub (STR,"(.) (.)","%2%1")--swap adjacent two characters. --[[Converts a string in "LaTeX" format to a string in "XML" format. "LaTeX": \command{some text} "XML": <command>some Text</command>]string. gsub (STR,"\ \ (%a+) {(.-)}","<%1>%2</%1>")string. Gsub (S,"^%s* (.-)%s*$","%1")--"trim" string extra spaces. --Calculates the value of the expression in "$[]" in the string. string. Gsub (S,"$ (%b[])", function (x) x ="Return"..string. Sub (x,2, -2)--Skip "[" and "]".         Localf =Load(x)returnF ()End)
Additional:

1, the "LaTeX" format of the string into the "XML" format of the string in the actual example,

s"the \\quote{task} is to \\em{change} that."-- 这里用"()"强制只保留"string.gsub()"的第一个返回值。print((string.gsub(s"\\(%a+){(.-)}""<%1>%2</%1>")))--> the <quote>task</quote> is to <em>change</em> that.

Quick mastery of Lua 5.3--string Library (2)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.