The following table lists all the character classes that LUA supports:
. Any character
%a Letter
%c Control character
%d numbers
%l Small Letter
%p Punctuation characters
%s white space character
%u capital letters
%w Letters and numbers
%x hex Digit
%z stands for 0 characters
There are some special characters in pattern matching
( ) . % + - * ? [ ^ $
% is used as the escape character for special characters, so '%. ' matches the character dot '. ', ' percent ' matches the character '% '.
The escape character '% ' can be used not only to escape special characters, but also for all non-alphabetic characters. When you have questions about a character, escape him with an escape character for security reasons.
+ Match previous character 1 or more times
* Match previous character 0 or more times
-Match previous character 0 or more times
? Match previous character 0 or 1 times
Example:
(1) Replace the non-letter in the string with the number '. '
< Span style= "Color:rgb (69,69,69); font-family:tahoma,helvetica,arial; font-size:14px; line-height:21px ">print (String.gsub (" Hello, up-down! ","%A ",". "))
and hello.. Up.down. 4
(the number 4 is not part of a string result, he is the second result returned by Gsub, representing the number of times the substitution occurred.) Other examples of printing gsub results will ignore this value)
< Span style= "Color:rgb (69,69,69); font-family:tahoma,helvetica,arial; font-size:14px; line-height:21px "> (2) '%d+ ' matches one or more numbers (integers):
i, j = String.find (" The number 1298 is even ","%d+ ")
--> print (I,J)--12
(3) Match date format
s = "Today is 30/05/1999, firm"
Print (String.sub (S, String.find (S, ""%d%d/%d%d/%d%d%d%d"))--30/05/1999
(4) Intercept the desired file name (the middle part of the file name may be jpg|png|jpeg|gif)
Local str1 = "WKgAgk1_M36eGCazAAHAC_MLulA790.jpg_200x200_2.jpg"
Local str2 = "WKgAgk1_M36eGCazAAHAC_MLulA790.png_200x200_2.jpg"
_,index1 = String.find (str1, "%.%a%a%a_")
_,index2 = String.find (str2, "%.%a%a%a_")
Print (String.sub (str1,1,index1-1))
--wkgagk1_m36egcazaahac_mlula790.jpg (matches the. jpg_ or. png_)
Print (String.sub (str2,1,index2-1))
- wkgagk1_m36egcazaahac_mlula790.png(matches the. jpg_ or. png_)
Print (String.gsub (str2, "_%d+x%d+_%d%.%a+", ""))
--> (matching is _200x200_2.jpg )
Other extensions:
Print ("==================="): Os.date (): "=======================")
--View CPU time:
Local x3 = Os.clock ()
Local s = 0
For i = 1, 100000 do
Path,_ = String.gsub (str2, "_%d+x%d+_%d%.%a+", "" ")
End
Local x4 = Os.clock ()
Print (String.Format ("Time-consuming:%.2f\n", x4-x3))
Lua Regular expression (string function)