2012-06-16 35 views
1

我想提取撇號之間的值,例如來自此字符串:package: name='com.app' versionCode='4' versionName='1.3'這就是開發android應用程序時「aapt」返回的值。我必須得到值com.app,41.3。我會很感激任何幫助:) 我發現this,但這是VBA。獲取C#中的撇號之間的值

+0

我已經知道了stirng.Split,但是我不想把它拆分成撇號,我想要它之間的值。 – P1nGu1n

+0

使用撇號作爲拆分字符,並且可以獲取撇號之間的值。你的數組將是'{「name =」,「com.app」,「versionCode =」,「4」...'。 –

回答

3

此正則表達式應該在所有情況下,假設'字符只發生爲值封閉性格:

string input = "package: name='com.app' versionCode='4' versionName='1.3'"; 
string[] values = Regex.Matches(input, @"'(?<val>.*?)'") 
         .Cast<Match>() 
         .Select(match => match.Groups["val"].Value) 
         .ToArray(); 
+0

謝謝,它的工作!這是一個非常聰明的解決方案,使用正則表達式! – P1nGu1n

+0

@ P1nGu1n:我稍微修改它以提高它的健壯性。改用新版本。 – Douglas

+0

再次感謝您的解決方案!但有什麼區別? – P1nGu1n

1
string strRegex = @"(?<==\')(.*?)(?=\')"; 
RegexOptions myRegexOptions = RegexOptions.None; 
Regex myRegex = new Regex(strRegex, myRegexOptions); 
string strTargetString = @"package: name='com.app' versionCode='4' versionName='1.3'"; 

foreach (Match myMatch in myRegex.Matches(strTargetString)) 
{ 
    if (myMatch.Success) 
    { 
    // Add your code here 
    } 
} 

RegEx Hero sample here.

1

如果你有興趣,這裏有一個您鏈接到的那個VBA的譯文:

public static void Test1() 
{ 
    string sText = "this {is} a {test}"; 
    Regex oRegExp = new Regex(@"{([^\}]+)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); 
    MatchCollection oMatches = oRegExp.Matches(sText); 
    foreach (Match Text in oMatches) 
    { 
     Console.WriteLine(Text.Value.Substring(1)); 
    } 
} 

也在VB.NET中:

Sub Test1() 
    Dim sText = "this {is} a {test}" 
    Dim oRegExp = New Regex("{([^\}]+)", RegexOptions.IgnoreCase Or RegexOptions.CultureInvariant) 
    Dim oMatches = oRegExp.Matches(sText) 
    For Each Text As Match In oMatches 
     Console.WriteLine(Mid(Text.Value, 2, Len(Text.Value))) 
    Next 
End Sub