Lua模式匹配找出跟在“Conference 10-”后面的4位数字。

我有一些字符串数据,需要搜索以找到特定的数字:

以下是一个示例字符串/缓冲区:

Conference 11-2222-a.b.c (1 member rate: 32000 flags: running|answered|enforce_min|dynamic|exit_sound|enter_sound) 176;014802813@mydomain;0182e4e4-193b-4d63-9bef-b597f0655c83;jdo ;014802813;hear|speak|talking|floor;0;0;0;0

Conference 10-1234.c.fdf.c (1 member rate: 32000 flags: running|answered|enforce_min|dynamic|exit_sound|enter_sound)175;.net/4122@mydomain;77c1f301-85e1-4275-9c539e5927b87d6;4122;hear|speak|talking|floor;0;0;0;0

我需要做的是搜索这个输出和“Conference 10-”后面的4位数字。在这种情况下,我需要的是1234。

我尝试过的

我尝试了以下所有模式...都没有给我我需要的内容:

  print(string.match(input, "10-%d%d%d%d-"));
  print(string.match(input, "Conference 10-%d%d%d%d-"));
  print(string.match(input, "Conference 10-(%d)-");
  print(string.match(input, "Conference 10(\-)(%d));

点赞
用户3832970
用户3832970

你需要使用转义连字符,因为未转义的连字符在Lua中是惰性量词(_-也可以表示0个或多个重复_)。

str =“Conference 11-2222-a.b.c(1成员费率:32000标志:running | answered | enforce_min | dynamic | exit_sound | enter_sound)176;014802813@mydomain;0182e4e4-193b-4d63-9bef-b597f0655c83;jdo ;014802813;hear|speak|talking|floor;0;0;0;0

会议10-1234.c.fdf.c(1成员费率:32000标志:running | answered | enforce_min | dynamic | exit_sound | enter_sound)175;.net/4122@mydomain;77c1f301-85e1-4275-9c539e5927b87d6;4122;hear | speak | talking | floor;0;0;0;0printstring.match(str,“Conference 10% -(%d%d%d%d)”))
                                      ^

这个将打印1234

Lua 20.2 - Patterns reference中可以得到:

一些字符被称为魔法字符,当在模式中使用时具有特殊意义。这些魔法字符是

( ) . % + - * ? [ ^ $

字符用作这些魔法字符的转义。

2015-11-26 21:13:31
用户256196
用户256196

使用 gsub():

print(string.gsub(".*Conference 10%-(%d%d%d%d)%-.*", "%1"));

使用 gsub() 函数:

print(string.gsub(".*Conference 10%-(%d%d%d%d)%-.*", "%1"));

注:gsub() 是 Lua 字符串库中的函数,可以在字符串中查找并替换文本。上面的例子是使用 gsub() 函数查找字符串中形如 "Conference 10-xxxx-" 的部分,并提取出字符序列 "xxxx",其中 x 表示数字。函数参数中的 %1 表示提取匹配到的第一个子字符串。print() 函数输出结果。

2015-11-26 21:15:57