2012-05-14 51 views
1

返回相同的發現模式目前我使用某種樹的那對每個級別一個正則表達式解析的任意文本文件轉換成樹。直到現在一切正常,並且正則表達式的結果放到了子節點上,以進一步解析文本。要獲得節點和子節點之間的鏈接,節點本身也有一個名稱,在正則表達式中用作組名稱。因此,在解析一些文本之後,我將得到一個包含一些命名組的正則表達式,並且節點本身也包含具有相同名稱的子節點,這導致了遞歸結構來執行一些任意解析。需要正則表達式模式在兩個不同的組名稱

現在我遇到了麻煩,導致使這種樹的處理在下一步稍微容易一些我需要的文本文件中的不同節點下我的樹中的非常相同的信息。由於事實上,這是也許有點費解,這裏是一個單元測試,顯示我想達到的目標:

string input = "Some identifier=Just a value like 123"; 
// ToDo: Change the pattern, that the new group 'anotherName' will contain the same text as 'key'. 
string pattern = "^(?'key'.*?)=(?'value'.*)$"; 
Regex regex = new Regex(pattern); 
Match match = regex.Match(input); 

var key = match.Groups["key"]; 
var value = match.Groups["value"]; 
var sameAsKeyButWithOtherGroupName = match.Groups["anotherName"]; 

Assert.That(key, Is.EqualTo(sameAsKeyButWithOtherGroupName)); 

任何想法如何得到這個工作?

回答

1

閱讀Cylians答案,寫我自己的意見給他後,我做了有關反向引用多一點研究,我的測試將與成功這個稍微改變的正則表達式:

string input = "Some identifier=Just a value like 123"; 
string pattern = @"^(?'key'.*?)(?'anotherName'\k<key>)=(?'value'.*)$"; 
Regex regex = new Regex(pattern); 
Match match = regex.Match(input); 

var key = match.Groups["key"]; 
var value = match.Groups["value"]; 
var sameAsKeyButWithOtherGroupName = match.Groups["anotherName"]; 

Assert.That(key, Is.EqualTo(sameAsKeyButWithOtherGroupName)); 

所以結論很簡單:如果你需要anoth下的同一個組呃名稱,簡單地聲明這個組,並使用另一個組的內容作爲模式字符串。

1

撥叫.NET模式的反向引用,必須指定\k<name_of_group>語法。可以試試這個:

bool foundMatch = false; 
try { 
    foundMatch = Regex.IsMatch(subjectString, @"^(?<authorName>(?'key'.*?)=\k<key>)$", RegexOptions.IgnoreCase | RegexOptions.Multiline); 
} catch (ArgumentException ex) { 
    // Syntax error in the regular expression 
} 

說明:

<!-- 
^(?<authorName>(?'key'.*?)=\k'key')$ 

Assert position at the beginning of the string «^» 
Match the regular expression below and capture its match into backreference with name 「authorName」 «(?<authorName>(?'key'.*?)=\k'key')» 
    Match the regular expression below and capture its match into backreference with name 「key」 «(?'key'.*?)» 
     Match any single character that is not a line break character «.*?» 
     Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?» 
    Match the character 「=」 literally «=» 
    Match the same text as most recently matched by the named group 「key」 «\k'key'» 
Assert position at the end of the string (or before the line break at the end of the string, if any) «$» 
--> 
+0

是的,我已經在正則表達式中讀過一些關於後向引用的內容,但我不知道如何在我的具體示例中使用它們。據我瞭解,它將允許您在同一個正則表達式中使用組的內容。但我需要在另一個組名下的內容。所以聽起來好像應該有可能,但直到現在我還沒有把握。如果你瞭解它,你能告訴我具體的表達,使我的上述測試工作? – Oliver