2012-03-07 44 views
2
string = myfx("{0}test123", test); 
string2 = myfx("actual string"); 

上面的行只是文本文件中幾行10行文本。我遍歷文本文件,並想知道是否有一個單一的正則表達式將覆蓋上面顯示的兩種情況。正則表達式可選字符

目標字符串是「test123」和「實際字符串」。有沒有辦法告訴正則表達式在發生時不要拉入「{0}」?

+0

很抱歉,如果這是一件顯而易見的,但什麼是'myfx'?所以你想匹配字符串「test123」和「實際字符串」..什麼是「{0}」與它有關? – 2012-03-07 00:30:51

+0

所以,你試圖解析一個非常特定的C#子集?你想得到什麼字符串的規則?線條究竟如何?你有什麼嘗試? – svick 2012-03-07 00:45:18

+0

除非myfx是變相的string.Format? – 2012-03-07 00:59:15

回答

1

要查找所有文本內部沒有大括號,使用正則表達式:

(?<=^|\})(?<!\{)[^\{\}]+(?<!\})(?=\{|$) 

測試:

Regex filter = new Regex(@"(?<=^|\})(?<!\{)[^\{\}]+(?<!\})(?=\{|$)"); 
string text = "Blah { Bleh} Blih {Bloh } Bluh"; 
foreach (Match match in filter.Matches(text)) 
{ 
    Console.WriteLine("\"{0}\"", match.Capture[0].Value); 
} 
Console.ReadLine(); 

輸出:

"Blah " 
" Blih " 
" Bluh" 

此方法仍有侷限性。它假定大括號是成對的。雖然有更多的工作可以做出不錯的選擇,但我希望它適合你的情況。

+0

你的正則表達式匹配「oops!」在''Blah {oops!} Bleh {1} Bloh''中,儘管它*在花括號內。 – 2012-03-07 02:19:53

+0

@IgorKorkhov,它的確如此。編輯... – 2012-03-07 04:16:41

+0

如果您可以假定花括號總是正確配對,那麼您只需:[^ {}] +(?![^ {}] *})''。但我不認爲這是OP所要求的。 – 2012-03-07 08:46:52

0

你可以使用:

string myfx = "{0}test123"; 
Regex regex = new Regex("(test123|actual string)"); 
string capturedValue = regex.Match(myfx).Captures[0].Value; 
+3

這太有點太過於字面值了,你不能假設所有幾十行都包含完全相同的文本。 – 2012-03-07 01:07:19

0

編輯:M42是正確的周邊沒有工作。

也許是:

string input = "{9}test123";//"regular string" 
var pattern = @"(?>\{\d\})?(?<target>[^""]+)"; 
var match = Regex.Match(input, pattern); 
string result = match.Groups["target"].ToString(); 
+0

由於其中的空間不匹配「實際字符串」。 – Toto 2012-03-07 09:24:39

+0

更改爲「非雙引號」.... – sweaver2112 2012-03-07 09:28:43