Lua learning (9)--Lua string

A string or string (String) is a string of characters consisting of numbers, letters, and underscores.
Strings in the Lua language can be represented in the following three ways:

  • A string of characters between single quotes .
  • A string of characters between double quotes .
  • A string of characters between [[ and ]] .
    String examples of the above three methods are as follows:
string1 = "Lua"
print("\"字符串 1 是\"",string1)
string2 = 'runoob.com'
print("字符串 2 是",string2)

string3 = [["Lua 教程"]]
print("字符串 3 是",string3)

The output of the above code execution is:

"字符串 1 是"    Lua
字符串 2 是    runoob.com
字符串 3"Lua 教程"

Escape characters are used to represent characters that cannot be displayed directly, such as the back key, the enter key, etc. For example, to convert double quotes in a string, you can use "\"".
All escape characters and their corresponding meanings:

write picture description here

String manipulation

Lua provides many methods to support string operations:
string.upper(argument): Convert
all strings to uppercase letters.

string.lower(argument): Convert
all strings to lowercase letters.

string.gsub(mainString,findString,replaceString,num)
replace in the string, mainString is the string to be replaced, findString is the character to be replaced, replaceString is the character to be replaced, num is the number of replacements (can be ignored, then all are replaced) ,Such as:

> string.gsub("aaaa","a","z",3);
zzza    3

string.find (str, substr, [init, [end]])
searches for the specified content in a specified target string (the third parameter is the index) and returns its specific position. Returns nil if it does not exist.

> string.find("Hello Lua user", "Lua", 1) 
7    9

string.reverse(arg)
string reverse

> string.reverse("Lua")
auL

string.format(…)

> string.format("the value is:%d",4)
the value is:4

string.char(arg) and string.byte(arg[,int])
char converts integer numbers into characters and concatenates them, byte converts characters into integer values ​​(a character can be specified, the default is the first character).

> string.char(97,98,99,100)
abcd
> string.byte("ABCD",4)
68
> string.byte("ABCD")
65
>

string.len(arg)
calculates the string length.

string.len("abc")
3

string.rep(string, n)
returns n copies of the string string

> string.rep("abcd",2)
abcdabcd

..
linking two strings

> print("www.runoob".."com")
www.runoobcom

string.gmatch(str, pattern)

Returns an iterator function that, each time this function is called, returns the next substring found in the string str that matches the pattern description. If the string described by the parameter pattern is not found, the iteration function returns nil.

for word in string.gmatch("Hello Lua user", "%a+") do 
    print(word) 
end

Hello
Lua
user

string.match(str, pattern, init)
string.match() only finds the first pair in the source string str. The parameter init is optional and specifies the starting point of the search process, the default is 1.
On successful pairing, the function returns all capture results in the pairing expression; if no capture flags are set, the entire pairing string is returned. When there is no successful pairing, nil is returned.

> = string.match("I have 2 questions for you.", "%d+ %a+")
2 questions

> = string.format("%d, %q", string.match("I have 2 questions for you.", "(%d+) (%a+)"))
2, "questions"

String case conversion

string1 = "Lua";
print(string.upper(string1))
print(string.lower(string1))

The result is:

LUA
lua

String Find and Reverse

string = "Lua Tutorial"
-- 查找字符串
print(string.find(string,"Tutorial"))
reversedString = string.reverse(string)
print("新字符串为",reversedString)

result:

5    12
新字符串为    lairotuT auL

string formatting

Lua provides the string.format() function to generate a string with a specific format. The first parameter of the function is the format, followed by various data corresponding to each code in the format.
Due to the existence of format strings, the readability of the resulting long strings is greatly improved. The format of this function is very similar to printf() in C language.
The following example demonstrates how to format strings:
The format string may contain the following escape codes:

%c - 接受一个数字, 并将其转化为ASCII码表中对应的字符

%d, %i - 接受一个数字并将其转化为有符号的整数格式

%o - 接受一个数字并将其转化为八进制数格式

%u - 接受一个数字并将其转化为无符号整数格式

%x - 接受一个数字并将其转化为十六进制数格式, 使用小写字母

%X - 接受一个数字并将其转化为十六进制数格式, 使用大写字母

%e - 接受一个数字并将其转化为科学记数法格式, 使用小写字母e

%E - 接受一个数字并将其转化为科学记数法格式, 使用大写字母E

%f - 接受一个数字并将其转化为浮点数格式

%g(%G) - 接受一个数字并将其转化为%e(%E, 对应%G)及%f中较短的一种格式

%q - 接受一个字符串并将其转化为可安全被Lua编译器读入的格式

%s - 接受一个字符串并按照给定的参数格式化该字符串

为进一步细化格式, 可以在%号后添加参数. 参数将以如下的顺序读入:
(1) 符号: 一个+号表示其后的数字转义符将让正数显示正号. 默认情况下只有负数显示符号.

(2) 占位符: 一个0, 在后面指定了字串宽度时占位用. 不填时的默认占位符是空格.

(3) 对齐标识: 在指定了字串宽度时, 默认为右对齐, 增加-号可以改为左对齐.

(4) 宽度数值

(5) 小数位数/字串裁切: 在宽度数值后增加的小数部分n, 若后接f(浮点数转义符, 如%6.3f)则设定该浮点数的小数只保留n位, 若后接s(字符串转义符, 如%5.3s)则设定该字符串只显示前n位.
string1 = "Lua"
string2 = "Tutorial"
number1 = 10
number2 = 20
-- 基本字符串格式化
print(string.format("基本格式化 %s %s",string1,string2))
-- 日期格式化
date = 2; month = 1; year = 2014
print(string.format("日期格式化 %02d/%02d/%03d", date, month, year))
-- 十进制格式化
print(string.format("%.4f",1/3))
string.format("%c", 83)            输出S
string.format("%+d", 17.0)              输出+17
string.format("%05d", 17)               输出00017
string.format("%o", 17)                 输出21
string.format("%u", 3.14)               输出3
string.format("%x", 13)                 输出d
string.format("%X", 13)                 输出D
string.format("%e", 1000)               输出1.000000e+03
string.format("%E", 1000)               输出1.000000E+03
string.format("%6.3f", 13)              输出13.000
string.format("%q", "One\nTwo")         输出"One\
                                          Two"
string.format("%s", "monkey")           输出monkey
string.format("%10s", "monkey")         输出    monkey
string.format("%5.3s", "monkey")        输出  mon

Converting characters to integers

The following example demonstrates the conversion of characters to and from integers:

-- 字符转换
-- 转换第一个字符
print(string.byte("Lua"))
-- 转换第三个字符
print(string.byte("Lua",3))
-- 转换末尾第一个字符
print(string.byte("Lua",-1))
-- 第二个字符
print(string.byte("Lua",2))
-- 转换末尾第二个字符
print(string.byte("Lua",-2))

-- 整数 ASCII 码转换为字符
print(string.char(97))

The result of executing the above code is:

76
97
97
117
117
a

Other common functions

string1 = "www."
string2 = "runoob"
string3 = ".com"
-- 使用 .. 进行字符串连接
print("连接字符串",string1..string2..string3)

-- 字符串长度
print("字符串长度 ",string.len(string2))

-- 字符串复制 2 次
repeatedString = string.rep(string2,2)
print(repeatedString)

The result of executing the above code is:

连接字符串    www.runoob.com
字符串长度     6runoobrunoob

match pattern

Matching patterns in Lua are directly described by regular strings. It is used for pattern matching functions string.find, string.gmatch, string.gsub, string.match.
You can also use character classes in pattern strings.
A character class is a pattern item that can match any character within a particular set of characters. For example, the character class %d matches any number. So you can use the pattern '%d%d/%d%d/%d%d%d%d' to search for dates in dd/mm/yyyy format:

s = "Deadline is 30/05/1999, firm"
date = "%d%d/%d%d/%d%d%d%d"
print(string.sub(s, string.find(s, date)))    --> 30/05/1999

The following table lists all character classes supported by Lua:
a single character (except ^$()%.[]*+-? ): paired with the character itself

.(点): 与任何字符配对

%a: 与任何字母配对

%c: 与任何控制符配对(例如\n)

%d: 与任何数字配对

%l: 与任何小写字母配对

%p: 与任何标点(punctuation)配对

%s: 与空白字符配对

%u: 与任何大写字母配对

%w: 与任何字母/数字配对

%x: 与任何十六进制数配对

%z: 与任何代表0的字符配对

%x(此处x是非字母非数字字符): 与字符x配对. 主要用来处理表达式中有功能的字符(^$()%.[]*+-?)的配对问题, 例如%%与%配对

[数个字符类]: 与任何[]中包含的字符类配对. 例如[%w_]与任何字母/数字, 或下划线符号(_)配对

[^数个字符类]: 与任何不包含在[]中的字符类配对. 例如[^%s]与任何非空白字符配对

When the above character class is written in uppercase, it is paired with any character that is not of this character class. For example, %S is paired with any non-whitespace character . For example, '%A' is a non-alphabetic character:

> print(string.gsub("hello, up-down!", "%A", "."))
hello..up.down.    4

The number 4 is not part of the string result, it is the second result returned by gsub and represents the number of times the substitution occurred.
There are some special characters in pattern matching, they have special meaning, special characters in Lua are as follows:

( ) . % + - * ? [ ^ $

'%' is used as an escape character for special characters, so '%.' matches a dot; '%%' matches the character '%'. The escape character '%' can be used not only to escape special characters, but also to all non-alphabetic characters.
A schema entry can be:

单个字符类匹配该类别中任意单个字符;

单个字符类跟一个 '*', 将匹配零或多个该类的字符。 这个条目总是匹配尽可能长的串;

单个字符类跟一个 '+', 将匹配一或更多个该类的字符。 这个条目总是匹配尽可能长的串;

单个字符类跟一个 '-', 将匹配零或更多个该类的字符。 和 '*' 不同, 这个条目总是匹配尽可能短的串;

单个字符类跟一个 '?', 将匹配零或一个该类的字符。 只要有可能,它会匹配一个;

%n, 这里的 n 可以从 19; 这个条目匹配一个等于 n 号捕获物(后面有描述)的子串。

%bxy,这里的x和y是两个明确的字符;这个条目匹配以x开始y结束,且其中x和 y保持平衡的字符串.意思是,如果从左到右读这个字符串,对每次读到一个x就+1,读到一个y就-1,最终结束处的那个y是第一个记数到0的y。举个例子,条目 %b() 可以匹配到括号平衡的表达式。

%f[set],指边境模式;这个条目会匹配到一个位于 set 内某个字符之前的一个空串,且这个位置的前一个字符不属于set。集合set的含义如前面所述。 匹配出的那个空串之开始和结束点的计算就看成该处有个字符 '\0' 一样。

Pattern:
Pattern refers to a sequence of pattern entries. Prepending the pattern with the symbol '^' will anchor the match from the beginning of the string. Add the symbol ' at the end of the pattern' will anchor the matching process to the end of the string. If '^' and '' appears in other places, and they have no special meaning, but only represent themselves.

Captures: A
pattern can enclose a subpattern within parentheses; these subpatterns are called captures. When a match succeeds, the substring in the string matched by the catch is saved for future use. Captures are numbered in the order of their opening parenthesis. For example, for the pattern "(a*(.)%w(%s*))", the part of the string that matches "a*(.)%w(%s*)" is saved in the first capture (hence number 1); the character matched by "." is catch number 2, and the part matched by "%s*" is number 3.
As a special case, an empty capture() will capture to the current string position (which is a number). For example, applying the pattern "()aa()" to the string "flaaap" would yield two captures: 3 and 5.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325643013&siteId=291194637