2011-04-14 144 views

回答

36

像這樣的東西應該這樣做:

string val = "name='40474740-1e40-47ce-aeba-ebd1eb1630c0'"; 

Match match = Regex.Match(val, @"'([^']*)"); 
if (match.Success) 
{ 
    string yourValue = match.Groups[1].Value; 
    Console.WriteLine(yourValue); 
} 

表達'([^']*)的說明:

' -> find a single quotation mark 
( -> start a matching group 
[^'] -> match any character that is not a single quotation mark 
* -> ...zero or more times 
) -> end the matching group 
+0

它非常有用的解釋。但爲什麼羣[1]? – liang 2013-09-16 05:23:09

+0

@liang第一組(match.Groups [0]')將包含整個正則表達式匹配的完整字符串。這意味着它還包含主要引用字符。 'match.Groups [1]'包含正則表達式中的第一個匹配組,因此這是我們想要使用的值。 – 2013-09-16 06:17:54

+0

不知道團體,但這正是幫助很多! +1 – feldeOne 2017-09-05 10:25:08

3

您正在尋找匹配GUID在使用正則表達式的字符串。

這是你想要的,我懷疑!

public static Regex regex = new Regex(
    "(\\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-"+ 
    "([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\\}{0,1})",RegexOptions.CultureInvariant|RegexOptions.Compiled); 

Match m = regex.Match(lineData); 
if (m.Succes) 
{ 
... 
} 
2

這將提取第一最後單引號之間的文本上一行:

string input = "name='40474740-1e40-47ce-aeba-ebd1eb1630c0'"; 
Regex regName = new Regex("'(.*)'"); 
Match match = regName.Match(input); 
if (match.Success) 
{ 
    string result = match.Groups[1].Value; 
    //do something with the result 
} 
+0

如果你有'a','b'這個人會得到一串「a」,「b」而不是可能的「a」。 @弗雷德裏克將會這樣做。 – 2012-07-18 17:18:06

0

你可以用積極的前瞻和回顧後也

string val = "name='40474740-1e40-47ce-aeba-ebd1eb1630c0'"; 

Match match = Regex.Match(val, @"(?<=')[^']*(?=')"); 
if (match.Success) 
{ 
    string yourValue = match.Groups[0].Value; 
    Console.WriteLine(yourValue); 
} 
相關問題