简体   繁体   中英

Parse string using Regular expression

i have this kind of string File type: Wireshark - pcapng so what i want is if my string start with File type: take and parse only Wireshark - pcapng

this is what i have try:

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

Instead of REGEX, use string.StartsWith method, something like:

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

You will get:

 Wireshark - pcapng

If you want to get rid of leading/trailing spaces from the resultant string then use string.Trim like:

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

Or if you just want to get rid of leading spaces then use string.TrimStart like:

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

Why don't you just remove File type: from your string:

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

Or you can check if the string starts with File type: and remove that part using string.Remove() :

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

This should do the trick:

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

so...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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