Step by step (LUA string Library)

Source: Internet
Author: User

1. Basic string functions:
Some functions in the string library are very simple, such:
1 ). String. Len (s) returns the length of string S;
2). String. Rep (S, N) returns the result of string s repeating n times;
3). String. Lower (s) returns a copy of S. all uppercase values are converted to lowercase, and other characters remain unchanged;
4). String. Upper (s) is the opposite of lower, converts lower case to upper case;
5). String. sub (S, I, j) extracts the I to J characters of string S. In Lua, the index value of the first character is 1, the last one is-1, and so on, such:
Print (string. sub ("[Hello world]", 2,-2 ))-- Output Hello World
6). String. Format (S,...) returns the formatted string. Its formatting rules are equivalent to the printf function in C language, for example:
Print (string. Format ("Pi = %. 4f", math. Pi ))-- Output Pi = 3.1416
7) The. String. Char (...) parameter is 0 to multiple integers, and each integer is converted to the corresponding character. Then return a string connected by these characters, such:
Print (string. Char (97,98, 99 ))-- Output ABC
8). String. byte (S, I) returns the ascii value of the I character of string S. If there is no second parameter, the ASCII value of the first character is returned by default.
Print (string. byte ("ABC "))-- Output 97
Print (string. byte ("ABC",-1 ))-- Output 99
Because all string-type variables are non-variable variables, in all string-related functions, the string value in the parameter cannot be changed, but a new value is generated and returned.

2. pattern matching function:
Lua's string Library provides a set of powerful pattern matching functions, such as find, match, gsub, and gmatch.
1). String. Find function:
Search for a pattern in the target string. If a pattern is found, the matching start index and end index are returned. Otherwise, Nil is returned. For example:

 1 S ="  Hello World  " 
2 I, j = String. Find (S, " Hello " )
3 Print (I, j) -- Output 1 5
4 I, j = String. Find (S," L " )
5 Print (I, j) -- Output 3 3
6 Print ( String. Find (S, " Lll " )) -- Output Nil

The string. Find function also has an optional parameter, which is an index used to tell the function where to start searching for the target string. It is mainly used to search for all matched sub-strings in the target string, and each search starts from the last found position. For example:

 1   Local T = {}
2 Local I = 0
3 While True Do
4 I = String. Find (S, " \ N " , I + 1 )
5 If I = Nil Then
6 Break
7 End
8 T [# T + 1 ] = I
9 End

2). String. Match function:
This function returns the matching part of the target string and the pattern string. For example:

 
1Date ="Today is 2012-01-01"
2D =String. Match(Date,"% D + \-% d +")
3 Print(D)--Output

3). String. gsub function:
This function has three parameters: Target string, mode, and replacement string. The basic usage is to replace all occurrences of the pattern in the target string with the replacement string. For example:
Print (string. gsub ("Lua is cute", "cute", "great "))-- Output Lua is great
This function also has an optional 4th parameter, that is, the actual number of replicas.
Print (string. gsub ("All LII", "L", "X", 1 ))-- Output Axl LII
Print (string. gsub ("All LII", "L", "X", 2 ))-- Output axx LII
The string. gsub function has another result, that is, the actual number of replicas.
Count = select (2, String. gsub (STR ,"","")) -- Output the number of spaces in Str

4). String. gmatch function:
Returns a function, which can be used to traverse all the places where the specified mode appears in a string. For example:

1 Words = {}
2 S = " Hello World "
3 For W In String. gmatch (S, " % A + " ) Do
4 Print (W)
5 Words [# words + 1 ] = W
6 End
7 -- Output result:
8 -- Hello
9 -- World

3. Mode:
The following list shows the currently supported mode metacharacters for Lua;

Mode metacharacters Description
. All characters
% Letter
% C Control characters
% D Number
% L Lowercase letters
% P Punctuation Marks
% S White space characters
% U Uppercase letters
% W Letters and numbers
% X Hexadecimal number
% Z Internal 0 characters

These metacharacters are capitalized to indicate their complementary sets. For example, % A indicates all non-letter characters.
Print (string. gsub ("Hello, up-down! "," % S ","."))-- Output hello... up. Down. 4
4 In the preceding example indicates the number of replicas.
In addition to the above metacharacters, Lua also provides several other key characters. For example :(). % + -*? [] ^ $
Where % Escape characters. For example, %. indicates the dot (.) and % indicates the percent sign (% ).
Square brackets [] You can create your own character categories by classifying different characters. For example, [% W _] indicates matching characters, numbers, and underscores.
Horizontal line ( - ) Indicates a connection range, for example, [0-9a-z]
If ^ Characters in square brackets, such as [^ \ n], indicate all characters except \ n, that is, the set of classes in square brackets. If ^ is not in square brackets, it indicates the start of a later character, $ Opposite to it, it indicates that the previous character ends. For example, ^ Hello % d $. The matched strings may be hello1 and hello2.
In Lua, four types of repeated parts are provided to modify the pattern, such: + (Repeated once or multiple times), * (repeated 0 or multiple times),-(repeated 0 or multiple times), and? (0 or 1 occurrence) . For example:
Print (string. gsub ("One, and two; and three", "% A +", "word "))-- Output word, word; WORD
Print (string. Match ("the number 1298 is even", "% d + "))-- Output 1298
Asterisk ( * ) And horizontal line ( - The main difference is that asterisks always try to match more characters, while hyphens always try to match the least characters.

 4. Capture ):
The capture function extracts content matching the pattern from the target string according to a pattern. In the specified capture, the part to be captured in the mode should be written into a pair of parentheses. For captured modes, the string. Match function returns all captured values as separate results. That is, it will cut the target string into multiple captured parts. For example:

 1 Pair ="  Name = Anna  " 
2 Key, value = String. Match (Pair, " (% A +) % S * = % S * (% A +) " )
3 Print (Key, value) -- Output name Anna
4
5 Date = " Today is 2012-01-02 "
6 Y, M, D = String. Match (Date, " (% D +) \-(% d +) " )
7 Print (Y, M, d) -- Output 2012 01 02

You can also use capture for the mode itself. That is% 1Indicates the first capture, and so on,% 0Indicates the entire match, for example:

 1   Print ( String. gsub ( "  Hello Lua  " , "  (.)(.)  " , "  % 2% 1  " )) -- The adjacent two characters are reversed and the output is ehll Oula.  
2 Print ( String. gsub ( " Hello Lua! " , " % " , " % 0-% 0 " )) -- Output is h-he-el-ll-lo-o l-lu-UA-!

5. replace:
String. the third parameter of the gsub function can be a string, a function, or a table. gsub calls this function every time it finds a match. The parameter used for the call is the captured content, and the return value of this function is the string to be replaced. When a table is called, String. gsub uses the content captured each time as the key, searches for it in the table, and uses the corresponding value as the string to be replaced. If the table does not contain this key, String. gsub does not change this match. For example:

 1   Function Expand (s)
2 Return ( String. gsub (S, " $ (% W +) " , _ G ))
3 End
4
5 Name = " Lua " ; Status = " Great "
6 Print (Expand ( " $ Name is $ status, isn' t it? " ))-- Output Lua is great, isn' t it?
7 Print (Expand ( " $ Othername is $ status, isn' t it? " )) -- Output $ othername is great, isn' t it?
8
9 Function Expand2 (s)
10 Return ( String. gsub (S, " $ (% W +) " , Function (N) Return Tostring ( _ G [N]) End ))
11 End
12
13 Print (Expand2 ( " Print = $ print; 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.