Lua Tutorial (14): A string library detailed _lua

Source: Internet
Author: User
Tags lowercase lua alphanumeric characters

1. Basic String function:

Some functions in the string library are simple, such as:

1). String.len (s) returns the length of the string s;
2). String.rep (S,n) Returns the result of the string s repeating n times;
3). String.Lower (s) returns a copy of S, in which all uppercase letters are converted to lowercase and the other characters are unchanged;
4). String.upper (s) and lower instead, convert lowercase to uppercase;
5). String.sub (S,I,J) extracts the first and first J characters of the string s. In Lua, the first character has an index value of 1, the last one is-1, and so on, such as:
Print (String.sub ("[Hello World], 2,-2)"--Output Hello World
6. String.Format (S,...) returns the formatted string whose formatting rules are equivalent to the printf function in C, such as:
Print (String.Format ("PI =%.4f", Math.PI))--Output PI = 3.1416
7. The String.char (...) parameter is 0 to multiple integers and converts each integer to the corresponding character. It then returns a string connected by these characters, such as:
Print (String.char (97,98,99))--Output ABC
8). String.byte (s,i) returns the ASCII value of the first character of the string s, and if there is no second argument, the default returns the ASCII value of the character.

Copy Code code as follows:

Print (String.byte ("abc"))--Output 97
Print (String.byte ("abc",-1))--Output 99

Because a variable of a string type is a variable of an immutable type, the string value in the argument cannot be changed in all string-related functions, but rather a new value is returned.

2. Pattern matching function:

The LUA string library provides a powerful set of pattern-matching functions, such as Find, match, Gsub, and Gmatch.

1). String.find function:
Searches for a pattern in the target string and, if found, returns a matching starting and ending index, otherwise returning nil. Such as:

Copy Code code as follows:

s = "Hello World"
I, j = string.find (S, "Hello")
Print (I, j)--Output 1 5
I, j = string.find (S, "L")
Print (I, j)--Output 3 3
Print (String.find (S, "lll"))--Output nil

The String.find function also has an optional argument, which is an index that tells the function where to start the search from the destination string. It is primarily used to search for all matching substrings in the target string, and each search begins at the last location that was found. Such as:

Copy Code code as follows:

Local T = {}
Local i = 0
While True
i = String.find (s, "\ n", i+1)
if i = = Nil Then
Break
End
t[#t + 1] = I
End

2). String.match function:

This function returns the part of the target string that matches the pattern string. Such as:

Copy Code code as follows:

Date = "Today is 2012-01-01"
D = string.match (date, "%d+\-%d+\-%d+")
Print (d)--output 2012-01-01

3). string.gsub function:

The function has 3 parameters, the target string, the pattern, and the replacement string. The basic use is to replace all occurrences of the pattern in the target string with a replacement string. Such as:

Copy Code code as follows:

Print (String.gsub ("Lua is cute", "cute", "great"))--Outputs the LUA is great

The function also has an optional 4th parameter, which is the number of actual substitutions.
Copy Code code as follows:

Print (String.gsub ("All Lii", "L", "X", 1))--Output Axl Lii
Print (String.gsub ("All Lii", "L", "X", 2))--Output Axx lii

The function String.gsub also has another result, the number of actual substitutions.
Count = Select (2, String.gsub (str, "", ""))--Output the number of Str hollow cells

4). String.gmatch function:

Returns a function through which the returned function can traverse all occurrences of the specified pattern in a string. Such as:

Copy Code code as follows:

Words = {}
s = "Hello World"
For W in String.gmatch (S, "%a+") does
Print (W)
words[#words + 1] = W
End
--The output result is:
--hello
--world

3. Mode:

The following list shows the schema meta characters currently supported by LUA;

The capitalization of these metacharacters represents their complement, such as%a, which represents all non-alphanumeric characters.

Copy Code code as follows:

Print (String.gsub ("Hello, up-down!", "%s", ".")) --Output hello.. Up.down. 4

4 in the example above indicates the number of substitutions.
In addition to the above meta characters, LUA provides several other key characters. such as: (). % + - * ? [ ] ^ $
Where% represents the escape character, such as%. Represents the point (.), percent%.
The brackets [] denote the classification of different characters to create their own character categories, such as [%w_] to represent matching characters, numbers, and underscores.

Horizontal line (-) indicates a range of connections, such as [0-9a-z]

If the ^ character is in square brackets, such as [^\n], which represents all characters except \ n, the complement of the category in square brackets. If ^ is not in square brackets, the expression begins with the following character, and the $ and it is the opposite, representing the end of the preceding character. For example: ^hello%d$, the matching string may be Hello1, Hello2, and so on.

In Lua, there are 4 repetitions that are used to decorate patterns, such as: + (repeat 1 or more times), * (repeat 0 or more times),-(repeat 0 or more times), and? (occurs 0 or 1 times). Such as:

Copy Code code as follows:

Print (String.gsub ("one, and two; and three ","%a+ "," word ")--output word, word Word; Word Word
Print (String.match ("The number 1298 is even", "%d+")--Output 1298

The main difference between an asterisk (*) and a horizontal line (-) is that the asterisk always tries to match more characters, while the horizontal line always tries to match the fewest characters.

4. Capture (Capture):

The capture feature extracts content that matches the pattern from the target string based on a pattern. In the specified capture, the part of the pattern that needs to be captured is written in a pair of parentheses. For a pattern with capture, the function String.match returns all the captured values as separate results. That is, it cuts the target string into more than one captured part. Such as:

Copy Code code as follows:

Pair = "name = Anna"
Key,value = String.match (Pair, "(%a+)%s*=%s* (%a+)")
Print (key,value)--Output name Anna

Date = "Today is 2012-01-02"
Y,m,d = String.match (date, "(%d+) \-(%d+) \-(%d+)")
Print (y,m,d)--Output 2012 01 02

You can also use capture for the pattern itself. That is,%1 represents the first capture, and so on,%0 represents the entire match, such as:

Copy Code code as follows:

Print (String.gsub ("Hello Lua", "(.) (.) ","%2%1 ")--swap adjacent two characters, output as Ehll Oula
Print (String.gsub ("Hello lua!", "%a", "%0-%0"))--Output as H-he-el-ll-lo-o l-lu-ua-a!

5. Replace:

The third parameter of the STRING.GSUB function can be either a string, a function, or a table, and if it is a function, String.gsub will call the function every time a match is found, when the argument is captured, and the return value of the function is the string to be replaced. When invoked with a table, String.gsub looks in the table with each captured content as key, and the corresponding value as the string to be replaced. If the key is not included in the table, then string.gsub does not change the match. Such as:

Copy Code code as follows:

function expand (s)
Return (String.gsub (S, "$ (%w+)", _g))
End

Name = "Lua"; Status = "Great"
Print (Expand ("$name is $status, isn ' t it?")) --Output The Lua is great, isn ' t it?
Print (Expand ("$othername is $status, isn ' t it?")) --Output $othername is great, isn ' t it?

function Expand2 (s)
Return (String.gsub (S, "$ (%w+)", function (n) return ToString (_g[n)))
End

Print (Expand2 ("print = $print; A = $a "))--Output print = FUNCTION:002B77C0; A = Nil

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.