2012-02-02 51 views
0

我的值是[A]。[B]。[C]。[D]和[X]。[Y]我想寫一個正則表達式,我在D之前的[]中的值(在上面的例子C中)和一個在[X]之後返回值的正則表達式(對於上面的例子Y)。正則表達式 - 在值之前或之後查找值

我正在使用C#,.net4。

回答

0

\[(.*?)\]\.\[D\] - 前D.獲取組1
\[X\]\.\[(.*?)\] - X.獲取組1

+0

不能使用(。*),因爲那會佔用太多,需要排除']'。 – 2012-02-02 21:14:26

+0

這是貪婪的情況。 。*?是懶惰的,會抓住,直到找到第一個字符。 – shift66 2012-02-02 21:16:52

+0

http://msdn.microsoft.com/en-us/library/3206d374.aspx#Greedy – shift66 2012-02-02 21:19:33

0

後第一:\ [([^ \ ]])*)\] \。\ [D \]

第二:\ [X \] \ \ [([^ \]] *)\]

1

這應該工作:

(?<=\[)\w(?=\]\.\[D\])

(?<=\[X\]\.\[)\w(?=\])

[Test] 
    public void TestC() 
    { 
     string input = "[A].[B].[C].[D].[X].[Y]"; 
     string actual = Regex.Match(input, @"(?<=\[)\w(?=\]\.\[D\])").Value; 
     string expected = "C"; 
     Assert.AreEqual(expected, actual); 
    } 

    [Test] 
    public void TestY() 
    { 
     string input = "[A].[B].[C].[D].[X].[Y]"; 
     string actual = Regex.Match(input, @"(?<=\[X\]\.\[)\w(?=\])").Value; 
     string expected = "Y"; 
     Assert.AreEqual(expected, actual); 
    } 
相關問題