2013-12-16 27 views
3

也许这个问题可能会混淆,我非常的n00b到正则表达式,我想我最好的,但没有成功。提取从字符串中的字,其是基于C#另一个字符串与正则表达式

我有以下文本

public const int A_KEY =    789; 
    public const int A_KEY1 =    123; 
    public const int A_KEY2 =    555; 

上面的字符串包含空格和空格。

我想这个数字基于键文本(A_Key的,或A_KEY1,或A_KEY2)(789或123或555)

如果我提供的A_Key我想789,依此类推。

我想是这样的:

string code = "A_KEY"; 
string pattern = @"[public const int " + code + @"] (\s) [=] \s (\d+)"; 
Regex reg = new Regex(pattern, RegexOptions.IgnoreCase); 
Console.WriteLine(pattern); 
Match m = reg.Match(text); 
if (m.Success) { 
    Console.WriteLine(m.Groups[2]); 
} 

哪里是我的错,我的正则表达式?

+1

正则表达式在哪里? – 2013-12-16 08:01:55

+0

我没有在你的代码中看到任何正则表达式。 –

+0

你能发表你正在使用的正则表达式吗? –

回答

2

您可以使用以下模式:

string pattern = @"public const int (?<Key>[\w\d_]+)\s+=\s+(?<Value>[\d]+)"; 

那么你将不得不每场比赛两个命名组(KeyValue)。您可以使用LINQ找到一个,例如A_KEY

var match = Regex.Matches(input, pattern) 
       .Cast<Match>() 
       .FirstOrDefault(m => m.Groups["Key"].Value == "A_KEY"); 
if (match != null) 
{ 
    var value = match.Groups["Value"].Value; 
} 
相关问题