Several key functions in the string library in Lua

Source: Internet
Author: User

Preface

As mentioned in Lua's database, we need to explain the pattern matching of the string library separately. String processing is a difficult and necessary knowledge point for any language learning. It's embarrassing to give you a string that allows you to process as needed. So, after reading some libraries in Lua and this article, I try to make it easier for you to process strings.

 

Speaking of pattern matching in Lua, it basically involves the following functions:

  • Find

  • Match

  • Gsub

  • Gmatch

In my summary, the above four functions are shown. Please let me know.

 

Simple and practical find

The string. Find () function is used to search for a pattern in a given target string. The simplest mode is a word, which only matches copies exactly the same as itself. When find finds a pattern, it returns two values: the starting and ending indexes that match. If no match is found, it returns nil. Sample Code:

123 local str = "Hello World"local i, j = string.find(str, "Hello") -- Returns the start position and end position of hello in Str.print(i, j)

The string. Find function also has an optional third parameter, which is an index that tells the function where to start searching for the target string. This setting is useful when we process the content that matches the given mode in a string. We can perform the search operation cyclically. Of course, here we only talk about the most common and simplest way. For the second parameter, we can pass a regular expression, that is, a pattern, for regular expression matching. Sample Code:

123 tr = "Hello12345World"local i, j = string.find(str, "%d+") print(i, j) -- 6   10

 

FIND's sibling match

The string. Match function is very similar to string. Find. It is also used to search for a mode in a string. The difference is that string. Match returns the molecular string that matches the pattern in the target string, not the location of the pattern. Sample Code:

123456789 local str = "Hello12345World"local subStr = string.match(str, "%d+") print(subStr)    local i, j =string.find(str, "%d+") subStr =string.sub(str, i, j) print(subStr)    -- Can match be considered as "find + sub?

Match and find are so similar. Therefore, in actual development, you need to decide which one to use.

 

Gsub

String. gsub has three parameters: Target string, mode, and replacement string. Its basic usage is to replace all occurrences of the pattern in the target string with the target string. Let's take a look at a short piece of code and understand everything.

123 local str = "Hello World"local strResult = string.gsub(str, "Hello""Jelly") print(strResult) -- Jelly World

In addition, gsub also has the fourth optional parameter, which can limit the number of replicas. The sample code is as follows:

1234567891011 local str = "Hello World"   -- There is no limit on the number of replicas.local strResult, cnt = string.gsub(str, "l""o") print(strResult) -- Heooo Worod Print (CNT) -- actual replacement times   -- Start to limit the number of replicasstrResult, cnt = string.gsub(str, "l""o", 1) print(strResult) -- Heolo World Print (CNT) -- replace once

Here, we also need to introduce the power of gsub. First read a piece of code and then introduce it again.

12345678910111213 local replaceTb = {hello = "Jelly", world = "Think"}    local str = "hello world"   -- Note that the first parameter is a tablelocal strResult = string.gsub(str, "hello", replaceTb) print(strResult) -- 1    strResult = string.gsub(strResult, "world", replaceTb) print(strResult) -- 2    strResult = string.gsub(strResult, "hello", replaceTb) print(strResult) -- 3

We can see that the third parameter of gsub is a table, that is, when the third parameter of gsub is a table, if the searched string contains content that matches the second parameter, the content will be used as the key and the value corresponding to the key will be searched in the table; if the table does not have this key, it will not be replaced; the above Code indicates this meaning. Next, let's take a look at some amazing code:

1234567 local replaceFunc = function (str)     return str .. "JellyThink"end local str = "hello world"-- Note that the first parameter is a tablelocal strResult = string.gsub(str, "hello", replaceFunc) print(strResult) -- 1

If no error is found, the third parameter of gsub can also be a function. The parameter of this function is a matched string, and the return value of this function will replace the matched content with the target string.

 

Unmeasurable gmatch

I don't know how to describe gmatch. gmatch will return an iterator function. You can use this iterator function to iterate all the Matching content. See the following code:

123456 local str = "Hello World"local iteratorFunc = string.gmatch(str, "%a+") -- % A + indicates matching all words   for i in iteratorFunc do    print(i) end

If you are not familiar with the iterator, see here. Now I am using find to implement a gmatch of our own. The function is similar to that of gmatch. The Code is as follows:

12345678910111213141516171819202122 local str = "Hello World"   -- Use Find to implement a gmatchlocal myGmatch = function (s, pattern)   Local resulttb ={} -- equivalent to a constant state in the iterator  Local index = 0 -- equivalent to the control variable in the iterator     local i, j = string.find(s, pattern)   while do    resultTb[#resultTb + 1] = string.sub(s, i, j)     i, j = string.find(s, pattern, j + 1)   end      return Function () -- returns an iterator Function    index = index + 1     return resultTb[index]   end end    for i in myGmatch(str, "%a+"do  print(i) end

 

Summary

Here we will summarize the functions that I think are important in this article. I think I have summarized it in detail. I should be able to understand it if I have written so many sample codes. That's it. I hope it will be useful to you. Finally, I hope you will share your learning experience with me and your it life and expectations...

 

Source: http://www.jellythink.com/archives/544

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.