正则表达式模式重复和捕获

3

最近我需要把propkeys.h(在C[++]中)翻译成C#。

我的目标是将以下内容转换为C#:

DEFINE_PROPERTYKEY(PKEY_Audio_ChannelCount, 0x64440490, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 7);

致:

public static PropertyKey Audio_ChannelCount = new PropertyKey(new Guid("{64440490-4C8B-11D1-8B70-080036B11A03}"));

我使用Notepad++进行正则表达式匹配,但是我也可以接受其他可脚本化的解决方案(如perl,sed)。请不要使用编译型语言(如C#,Java...)。
最终我得到了这个(有效):
// TURNS GUID into String
// Find what (Line breaks inserted for convenience):
0x([[:xdigit:]]{8}),\s*0x([[:xdigit:]]{4}),\s*0x([[:xdigit:]]
{4}),\s*0x([[:xdigit:]]{2}),\s*0x([[:xdigit:]]{2}),\s*0x([[:xdigit:]]
{2}),\s*0x([[:xdigit:]]{2}),\s*0x([[:xdigit:]]{2}),\s*0x([[:xdigit:]]
{2}),\s*0x([[:xdigit:]]{2}),\s*0x([[:xdigit:]]{2})

// Replace with:
new Guid\("{$1-$2-$3-$4$5-$6$7$8$9$10$11}"\)

// Final pass
// Find what:
^DEFINE_PROPERTYKEY\(PKEY_(\w+),\s*(new Guid\("\{[[:xdigit:]|\-]+"\)),\s*\d+\);$
// Replace with:
public static PropertyKey $1 = new PropertyKey\($2\);

虽然这个方法可行,但我觉得第一遍的结果有点奇怪。我想用一个重复的{1}来代替成堆的{2}。

(0x([[:xdigit:]]){2},\s*)+

但无法将其与群组一起使用。有人能告诉我如何使用正则表达式以“标准”方式完成此操作吗?
1个回答

0

不幸的是,当您使用量词进行匹配时,该组将匹配整个文本,因此更“优雅”的解决方案是使用等效于Perl的\G元字符,它从上一个匹配结束后开始匹配。您可以使用类似以下的代码(Perl):

my $text = "DEFINE_PROPERTYKEY(PKEY_Audio_ChannelCount, 0x64440490, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 7);";
my $res = "public static PropertyKey Audio_ChannelCount = new PropertyKey(new Guid(\"{";

if($text =~ m/0x((?:\d|[A-F]){8}),\s*0x((?:\d|[A-F]){4}),\s*0x((?:\d|[A-F]){4})/gc)
{
   $res .= $1 . "-" . $2 . "-" . $3 . "-";
}

if($text =~ m/\G,\s*0x((?:\d|[A-F]){2}),\s*0x((?:\d|[A-F]){2})/gc)#
{
   $res .= $1 . $2 . "-";
}

while($text =~ m/\G,\s*0x((?:\d|[A-F]){2})/gc)
{
   $res .= $1;
}

$res .= "}\"))";

print $res . "\n";

之后您应该在 $res 上有结果字符串。当运行此脚本时,我的输出为:

public static PropertyKey Audio_ChannelCount = new PropertyKey(new Guid("{64440490-4C8B-11D1-8B70-080036B11A03}"))

免责声明:我不是 Perl 程序员,如果此代码中存在任何实质性错误,请随时纠正。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接