使用正则表达式从基于C#中另一个字符串的字符串中提取一个单词
也许这个问题会让人困惑,我对Regex非常不了解,我正在尽最大努力,但没有成功 我有以下文本:使用正则表达式从基于C#中另一个字符串的字符串中提取一个单词,c#,regex,C#,Regex,也许这个问题会让人困惑,我对Regex非常不了解,我正在尽最大努力,但没有成功 我有以下文本: public const int A_KEY = 789; public const int A_KEY1 = 123; public const int A_KEY2 = 555; 上面的字符串包含空格和空格 我想根据一个键文本(a_键,或a_键1,或a_键2)获取该数字(789或123或555) 如
public const int A_KEY = 789;
public const int A_KEY1 = 123;
public const int A_KEY2 = 555;
上面的字符串包含空格和空格
我想根据一个键文本(a_键,或a_键1,或a_键2)获取该数字(789或123或555)
如果我提供密钥,我想得到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]+)";
我在你的代码中没有看到任何正则表达式。你能发布你正在使用的正则表达式吗?如果没有
模式
的值,我们假定你用来初始化reg
,我们将无法判断。@ChristmasUnicorn:post updated,很抱歉丢失了这个值。
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;
}