简体   繁体   English

从字符串中提取数字,后跟“ I-”

[英]Extract number from a string followed by “I-”

In C#, I assigned this last line from a log file to string "str" I want to extract the numbers following "I-" and store it in a data type for use it later in the program. 在C#中,我将日志文件的最后一行分配给字符串“ str”,我想提取“ I-”之后的数字并将其存储为数据类型,以供以后在程序中使用。 In the example below I need to get 667466. 在下面的示例中,我需要获取667466。
Please help how to do this? 请帮忙怎么做?

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\" }"

You can use regex to find this data. 您可以使用正则表达式查找此数据。

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
}

Personally I like Uladzimir's regex solution, but here's an alternative: 我个人喜欢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);

This only works on strings specifically formatted like you have though, the regex solution is more generalizable. 不过,这仅适用于像您一样格式化的字符串,正则表达式解决方案更具通用性。 You can upgrade this version to make output a StringBuilder instead of a string too. 您可以升级此版本以使output是StringBuilder而不是字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM