2013-07-31 105 views
3

我最近不得不在C#中翻譯propkeys.h(在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}")); 

我用記事本+ +的正則表達式,但我接受任何其他腳本化解決方案(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\); 

雖然這是工作,我覺得第一遍一些奇怪的。我想用重複的替換{2}噸。 類似於:

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

但無法讓它與羣組一起工作。有人能告訴我用正則表達式來做這個「標準」方法嗎?

回答

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程序員,所以如果有這個代碼任何實質性錯誤,請隨時糾正他們