使用正则表达式找到 Lua 字符串

目前我们需要找出 Lua 文件中的字符串。我写了这个正则表达式:

\\[\\[[^\\[\\]]*\\]\\]|"[^\\"]*"

但它不太好,不能匹配包含 "["、"]" 或 "\"" 的字符串。

有人能帮忙吗?

点赞
用户1442917
用户1442917

我发现删除斜杠比尝试使用正则表达式来处理它们更容易(这可能需要负向后瞻表达式)。由于您使用的是正则表达式(而不是 Lua 模式),在 Perl 中可以使用类似这样的东西:

for my $s (qw([[text]more]] [=[text]]more]=] [=[text]] 'text' 'text\'more' 'text\\\\'more' "text" "text\"more" "text\\\\"more" "text'more")) {
  (my $c = $s) =~ s/\\\\/  /g; # remove escaped slashes
  $c =~ s/\\./  /g; # removed escaped non-slashes as they make no difference for string well-formedness
  print("$s => ", $c =~ m/^(?:\[(=*)\[.*?\]\1\]|'[^']*'|"[^"]*")$/ ? 1 : 0, "\n");
}

这将打印:

[[text]more]] => 1
[=[text]]more]=] => 1
[=[text]] => 0
'text' => 1
'text\'more' => 1
'text\\'more' => 0
"text" => 1
"text\"more" => 1
"text\\"more" => 0
"text'more" => 1

2015-10-20 06:24:28
用户2045424
用户2045424

经过多次尝试,这个正则表达式对我起作用:

(?<!--)\[(=*)\[.*?\]\1\]|"((\\.)|[^"\\])*?"|'((\\.)|[^'\\])*?'

匹配 Lua 的“长括号”字符串语法:

\[(=*)\[.*?\]\1\]
2015-10-20 09:00:24