lua中字符串匹配笔记

在program in lua 中 %w+的具体含义是什么?通过查询得知

local s,e = string.find(line,"%w+",pos)

模式串

.   任意字符 
%a   字母 
%c   控制字符 
%d   数字 
%l   小写字母 
%p   标点字符 
%s   空白符 
%u   大写字母 
%w   字母和数字 
%x   十六进制数字 
%z   代表 0的字符 

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

[] 该方框作为匹配该范围的集合,。
  如[0-9] 则匹配0到9的数字范围

Lua 中的模式修饰符有四个: 
+   匹配前一字符 1 次或多次,最长匹配
*   匹配前一字符 0 次或多次,最长匹配
-   匹配前一字符 0 次或多次,最短匹配
?   匹配前一字符 0 次或 1次 
'+',匹配一个或多个字符,总是进行最长的匹配。

如,模式  '%a+'  匹配一个或多个字母或者一个单词。

     模式  '%w+'  匹配一个或多个字母数字以及字母数字的结合。

string.gsub 函数有三个参数:目标串,模式串,替换串。
基本作用是用来查找匹配模式的串,并将使用替换串其替换掉: 

string.gsub 函数有三个参数:目标串,模式串,替换串。
基本作用是用来查找匹配模式的串,并将使用替换串其替换掉: 

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

string.gsub 的第二个返回值表示进行替换操作的次数。例如,
下面代码计字符串中空格出现的次数: 

_, count = string.gsub("test test", " ", " ") 
_ 表示哑元变量


如:匹配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 


<think>首先,用户的问题是:“我想查找关于Lua语言中匹配字符串的方法或示例,请问luastringmatchingexample”。这是关于Lua编程语言中字符串匹配的示例或方法。用户提供了几个引用:-引用[1]:讨论了string.rep函数。-引用[2]:讨论了string.find函数。-引用[3]:讨论了string.gmatch函数。-引用[4]:讨论了Luapatterns,包括锚点字符(^和$)。-引用[5]:讨论了string.gsub函数。系统指令要求:-所有行内数学表达式使用$...$格式。-独立公式使用$$...$$格式并单独成段。-LaTeX语法正确。-使用中文回答。-生成相关问题。-回答中引用的段落末尾添加引用标识如[^1]。用户的需求是Lua字符串匹配的例子,所以我应该专注于Lua字符串模式匹配功能。从引用中,关键函数包括string.find,string.match,string.gmatch,string.gsub等。常见的功能有查找、迭代、替换等。主要从引用中提取:-string.find:查找模式在字符串中的位置。-string.gmatch:迭代字符串中的匹配。-string.gsub:替换字符串中的匹配Lua的模式匹配是基于模式的,类似于正则表达式但更简单(称为Luapatterns)。引用[4]提到了模式的开头和结尾锚点:^表示开头,$表示结尾。回答结构:1.解释Lua字符串匹配的基本概念。2.提供示例代码。3.基于引用添加引用标识。4.结束时生成相关问题。步骤:-使用中文回答。-示例代码需要用代码块(如示例中的Python代码)。-解释每个函数的用法。潜在内容:-基本查找:使用string.find。-捕获匹配:使用string.match。-迭代匹配:使用string.gmatch。-替换匹配:使用string.gsub。-模式语法:如%a+表示一个或多个字母。生成相关问题:-类似于用户之前的问题,生成3-5个相关问题,如优化、应用场景等。最终输出结构:1.介绍和示例。2.代码示例。3.相关问题。确保回答真实可靠:基于Lua文档和常识。引用标识添加到引用来源。</think> ### Lua字符串匹配方法和示例 在Lua语言中,字符串匹配主要基于内置的字符串库函数和简单的模式(Patterns),不同于正则表达式但功能强大。这些函数可用于查找、迭代或替换字符串中的特定模式。以下是一些关键方法和实际示例,基于您的引用材料。 #### 1. **字符串查找(`string.find`)** `string.find` 用于在字符串中查找模式的第一个匹配位置。如果找到,返回匹配的开始和结束索引;否则返回 `nil`。 - **示例**:查找 "Lua" 在 "Hello Lua user" 中的位置。 ```lua local s = "Hello Lua user" local start, finish = string.find(s, "Lua") print(start, finish) -- 输出:7 9 ``` 该示例演示了如何获取匹配位置的索引[^2]。 #### 2. **模式迭代(`string.gmatch`)** `string.gmatch` 返回一个迭代器,用于在字符串中遍历所有匹配的模式。它特别适合处理多个重复匹配,如单词或键值对。 - **示例1**:迭代字符串中的单词(模式 `%a+` 表示一个或多个字母字符)。 ```lua local s = "hello world from Lua" for word in string.gmatch(s, "%a+") do print(word) -- 输出:hello, world, from, Lua(每个单词一行) end ``` - **示例2**:从字符串中提取键值对(模式 `(%w+)=(%w+)` 使用捕获组)。 ```lua local s = "from=world, to=Lua" local t = {} for k, v in string.gmatch(s, "(%w+)=(%w+)") do t[k] = v -- t["from"] = "world", t["to"] = "Lua" end ``` 这些示例展示了如何利用模式捕获复杂数据[^3]。 #### 3. **模式替换(`string.gsub`)** `string.gsub` 用于替换字符串中所有匹配的模式,可通过函数或表自定义替换行为。 - **示例1**:基本替换(模式 `Lua` 替换为 `Python`)。 ```lua local s = "Hello Lua user" local new_str = string.gsub(s, "Lua", "Python") print(new_str) -- 输出:Hello Python user ``` - **示例2**:使用函数作为替换(模式 `%d+` 表示一个或多个数字)。 ```lua local s = "Prices: 10, 20, 30" local new_str = string.gsub(s, "%d+", function(num) return tonumber(num) * 2 end) print(new_str) -- 输出:Prices: 20, 40, 60 ``` 这体现了动态替换的灵活性[^5]。 #### 4. **模式锚点(特殊字符 `^` 和 `$`)** Lua 模式支持锚点字符来指定匹配位置:`^` 表示字符串开头,`$` 表示字符串结尾。 - **示例**:检查字符串是否以数字开头(模式 `^%d`)。 ```lua local s = "123abc" if string.find(s, "^%d") then print("Starts with digit") -- 输出:Starts with digit end ``` 这可用于验证输入格式[^4]。 ### 关键技巧 - **模式语法**:Lua 模式比正则表达式简单。例如: - `%a` 匹配字母(等价于 `[a-zA-Z]`)。 - `%d` 匹配数字(等价于 `[0-9]`)。 - `%s` 匹配空白字符。 - 使用捕获组 `(...)` 来提取子字符串[^3][^4]。 - **性能**:对于简单任务,Lua 模式高效且资源友好;复杂匹配时,`string.gmatch` 优于循环调用 `string.find`[^5]。 - **注意**:`string.gmatch` 中 `^` 不能作为锚点,否则会中断迭代[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值