也许这个问题可能令人困惑,我对Regex非常满意,我正在尽力而为,但没有成功。
我有以下文字:
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] );
}
我的正则表达式在哪里出错?
您可以使用以下模式:
string pattern = @"public const int (?<Key>[\w\d_]+)\s+=\s+(?<Value>[\d]+)";
那么每个匹配项将有两个命名的组(Key
和Value
)。您可以使用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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句