[英]Extract number from a string followed by “I-”
在C#中,我将日志文件的最后一行分配给字符串“ str”,我想提取“ I-”之后的数字并将其存储为数据类型,以供以后在程序中使用。 在下面的示例中,我需要获取667466。
请帮忙怎么做?
string str = "2017-01-16 11:10:37.151 +11:00 [Information] OutboundMessageFile:MessageFields: [KeyValuePair`2 { Key: \"ConfirmationCode\", Value: \"I-667466\" }], MessageAttachments: \"\", MessageConfig: \"\", MachineName: \"MARYDEV234\" }"
您可以使用正则表达式查找此数据。
var regex = new Regex("Value: \"I-(\\d+)\"");
var match = regex.Match(str);
if (match.Success)
{
var data = match.Groups[1].Value;
// Store data for next use
}
我个人喜欢Uladzimir的正则表达式解决方案,但这里有一个替代方案:
string str = "2017-01-16 11:10:37.151 +11:00 [Information] OutboundMessageFile:MessageFields: [KeyValuePair`2 { Key: \"ConfirmationCode\", Value: \"I-667466\" }], MessageAttachments: \"\", MessageConfig: \"\", MachineName: \"MARYDEV234\" }";
int index = str.IndexOf("I-");
index += 2; //Skip the "I-"
string output = "";
for(int i = index; true; i++)
{
if(str[i] == '"')
break;
output += str[i];
}
Console.WriteLine(output);
不过,这仅适用于像您一样格式化的字符串,正则表达式解决方案更具通用性。 您可以升级此版本以使output
是StringBuilder而不是字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.