正则表达式找出Lua字符串

时间:2015-10-20 05:13:57

标签: regex lua

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

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

但它不够好,它与包含“[”或“]”或“\”“的字符串不匹配。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

我发现删除斜杠更容易,而不是尝试使用正则表达式来处理它们(这可能需要负面的lookbehind表达式)。由于你使用的是正则表达式(而不是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

答案 1 :(得分:0)

经过多次尝试,这个正则表达式对我有用: (?<!--)\[(=*)\[.*?\]\1\]|"((\\.)|[^"\\])*?"|'((\\.)|[^'\\])*?'

匹配Lua的“长括号”字符串语法 (?<!--)\[(=*)\[.*?\]\1\]|"((\\.)|[^"\\])*?"|'((\\.)|[^'\\])*?'