使用正则表达式解析字符串

时间:2013-04-22 10:50:45

标签: c#

我有这种字符串File type: Wireshark - pcapng 所以我想要的是,如果我的字符串以File type:开头,只需解析Wireshark - pcapng

这就是我的尝试:

var myString = @":\s*(.*?)\s* ";

3 个答案:

答案 0 :(得分:7)

使用string.StartsWith方法代替REGEX,例如:

if(str.StartsWith("File type:"))
   Console.WriteLine(str.Substring("File type:".Length));

你会得到:

 Wireshark - pcapng

如果您想从结果字符串中删除前导/尾随空格,请使用string.Trim,如:

Console.WriteLine(str.Substring("File type:".Length).Trim());

或者,如果您只想摆脱前导空格,请使用string.TrimStart,如:

Console.WriteLine(str.Substring("File type:".Length).TrimStart(' '));

答案 1 :(得分:1)

为什么不从字符串中删除File type:

str = str.Replace("File type: ",string.Empty);

或者您可以检查字符串是否以File type:开头,并使用string.Remove()删除该部分:

if(str.StartsWith("File type: "){
    str=str.Remove(11); //length of "File Type: "
}

答案 2 :(得分:0)

这应该可以解决问题:

(?<=^File type: ).*$

所以...

var match = Regex.Match("File type: Wireshark - pcapng", @"(?<=^File type: ).*$");
if(match.Success)
{
    var val = match.Value;
    Console.WriteLine(val);
}