[英]Extract a word from string which is based on another string in C# with 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.