lua 字符串 正則表達式 轉義 特殊字符


string.gsub 函數有三個參數:目標串,模式串,替換串。
基本作用是用來查找匹配模式的串,並將使用替換串其替換掉: 

s = string.gsub("Lua is good", "good", "bad?") 
print(s)   --> Lua is bad

string.gsub 的第二個返回值表示進行替換操作的次數。例如,
下面代碼計字符串中空格出現的次數: 

_, count = string.gsub("test test", " ", " ") 
_ 表示啞元變量

模式串
.   任意字符 
%a   字母 
%c   控制字符 
%d   數字 
%l   小寫字母 
%p   標點字符 
%s   空白符 
%u   大寫字母 
%w   字母和數字 
%x   十六進制數字 
%z   代表 0的字符 


特殊字符如下:
(). % + - * ? [ ^ $ 
% 也作為以上特殊字符的轉義字符。

[] 該方框作為匹配該范圍的集合,。
  如[0-9] 則匹配0到9的數字范圍

Lua 中的模式修飾符有四個: 
+   匹配前一字符 1 次或多次,最長匹配
*   匹配前一字符 0 次或多次,最長匹配
-   匹配前一字符 0 次或多次,最短匹配
?   匹配前一字符 0 次或 1次 
'+',匹配一個或多個字符,總是進行最長的匹配。
如,模式  '%a+'  匹配一個或多個字母或者一個單詞: 

注意以上的區別:

如:匹配c中的注釋串
用 '/%*.*%*/'  和'/%*.-%*/'

str = "int x; /* x */  int y; /* y */" 
print(string.gsub(str, "/%*.*%*/", "<注釋串>")) 
  --> int x; <注釋串> 
采用 '.-' 則為最短匹配,即匹配 "/*" 開始到第一個 "*/"  之前的部分: 
str = "int x; /* x */  int y; /* y */" 
print(string.gsub(str, "/%*.-%*/", "<注釋部分>")) 
  --> int x; <注釋串>  int y; <注釋串> 

以 '^'  開頭表示只匹配目標串的開始部分,
以 '$'  結尾表示只匹配目標串的結尾部分。

%b 表示匹配對稱字符,注意其只能針對的ansi碼單字符。
x = string.gsub("xdddddyxxx", "%bxy", "取代")
print(x)   -->取代xxx

如去除字符串首尾的空格: 
function trim (s) 
  return (string.gsub(s, "^%s*(.-)%s*$", "%1")) 
end 


---------------------------------

看原文中的gsub注釋:相當詳細,不過對於模式解釋補充在上。

string.gsub (s, pattern, repl [, n])

Returns a copy of s in which all occurrences of the pattern 
have been replaced by a replacement string specified by repl,
which may be a string, a table, or a function. 
gsub also returns, as its second value, the total number of substitutions made.

repl是字符串,則為替換。 如果在參數前有%則表示符合匹配的字符串
If repl is a string, then its value is used for replacement. 
The character % works as an escape character:
any sequence in repl of the form %n, with n between 1 and 9, stands for the 
value of the n-th captured substring (see below). 
The sequence %0 stands for the whole match. The sequence %% stands for a single %.


repl作為表參數
If repl is a table, then the table is queried for every match, 
using the first capture as the key; if the pattern specifies 
no captures, then the whole match is used as the key.

如果參數為函數,則每次匹配成功則調用該函數
If repl is a function, then this function is called every 
time a match occurs, with all captured substrings passed 
as arguments, in order; 

if the pattern specifies no captures,
then the whole match is passed as a sole argument.

If the value returned by the table query or by the function call is a string or a number, 
then it is used as the replacement string; otherwise, if it is false or nil, 
then there is no replacement (that is, the original match is kept in the string).

參數n則限制最大
The optional last parameter n limits the maximum number of substitutions to occur.


舉例:
   %1 表示符合模式的第一個匹配
   x = string.gsub("hello world", "(%w+)", "%1 %1")
   --> x="hello hello world world"
     
   第4項
   x = string.gsub("hello world", "%w+", "%0 %0", 1)
   --> x="hello hello world"
   
   hello 和from作為模式中左匹配為%1,world 和lua為右匹配,為%2
   x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
   --> x="world hello Lua from"

   替換 以$打頭的字符串
   x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
   --> x="home = /home/roberto, user = roberto"
   
   參數為函數類型
   x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
           return loadstring(s)()
         end)
     --> x="4+5 = 9"
     
    參數為表類型
   local t = {name="lua", version="5.1"}
   x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
   --> x="lua-5.1.tar.gz"

==============================
gmatch 的用法:
在模式符合匹配多次時
Returns an iterator function that, each time it is called,
returns the next captures from pattern over string s. 
If pattern specifies no captures, then the whole match 
is produced in each call.

看例子:
   s = "hello world from Lua"
   for w in string.gmatch(s, "%a+") do
      print(w)
   end
  
采用gmatch來解析到表類型
     t = {}
     s = "from=world, to=Lua"
     for k, v in string.gmatch(s, "(%w+)=(%w+)") do
       t[k] = v
     end

一個http傳送參數的應用
URL 編碼,
這種編碼將一些特殊字符(比  '=' '&' '+')轉換為"%XX"形式的編碼,
XX是字符的16進制表示,空白為'+'。
如,將"a+b = c"  編碼為 "a%2Bb+%3D+c" 
一個典型的參數串:
name=al&query=a%2Bb+%3D+c&q=yes+or+no 

1先把空格和16進制編碼轉換為ansi碼
function convet1(s) 
  s = string.gsub(s, "+", " ") 
  s = string.gsub(s, "%%(%x%x)", function (h) 
   return string.char(tonumber(h, 16)) 
  end) 
  return s 
end 

2.解析參數串
p = {} 
function decode (s) 
  for name, value in string.gmatch(s, "([^&=]+)=([^&=]+)") do 
  name = unescape(name) 
  value = unescape(value) 
  p[name] = value 
  end 
end 

3.正則表達式解析(匹配)字符串

local str = [[您尾號為 348503的賬號於 11月24日 09時22分充值成功,金額100元,訂單號:2517112409224508【愛你一萬年】]]

function getMatchTxt(str,pattern)
for txt in string.gmatch(str, pattern) do
return txt
end
end
print(getMatchTxt(str,"您尾號為 ([%d]+)的賬號")) -- echo:348503


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM