Lua string replacement function string. gsub (S, Pat, REPL [, N])

Source: Internet
Author: User

Lua string replacement function string. gsub (S, Pat, REPL [, N])

Link: http://blog.csdn.net/zhangxaochen/article/details/8085484

Function prototype string. gsub (S, Pat, REPL [, N])

This is what global means to replace the substring globally.
S: Source string
Pat: pattern, matching mode
Repl: replacement, replace the string matched by Pat with repl
[, N]: optional, indicating that only the first n characters of the source string are viewed.

For example, write a trim function:

Function trim (s) Return (string. gsub (S, "^ % S *(. -) % S * $ "," % 1 ") end ---- then call: S = '\ t a BC d' print (TRIM (s) ----- output: a bc d, starts with \ t, and spaces at the end are all truncated by trim

Here are some explanations:
1. Return (string. gsub (...). Note that there is a bracket outside string. gsub. In fact, two values are returned after gsub is called. One is the replaced string, and the other is the number of replacement times. Once parentheses are added, only the first value is returned, that is, the replaced string. You can try to remove the outer parentheses to see what is output

2. The matching mode string "^... $" indicates that the entire string is matched. ^ Starts with a table, and $ indicates the end. Here, the effect of (.-) is the same as that of (. *), because it matches from the beginning of the string to the end.
If ^ and $ are removed, the entire string is not matched. Under the action of (.-), the output is: ABCD.
Link: http://blog.csdn.net/zhangxaochen/article/details/8085484

{Over }}

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.