从C#中的文本中提取特殊字符


Microsoft Windows [Version 10.0.19042.631]
(c) 2020 Microsoft Corporation. All rights reserved.
C:Usersamir8OneDriveDesktopC#CmdCommandCmdCommandbinDebugnet5.0-windows>ping google.com
Pinging google.com [172.217.18.142] with 32 bytes of data:
Reply from 172.217.18.142: bytes=32 **time=90ms** TTL=127
Reply from 172.217.18.142: bytes=32 **time=83ms** TTL=127
Reply from 172.217.18.142: bytes=32 **time=71ms** TTL=127
Reply from 172.217.18.142: bytes=32 **time=70ms** TTL=127
Ping statistics for 172.217.18.142:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 70ms, Maximum = 90ms, Average = 78ms
C:Usersamir8OneDriveDesktopC#CmdCommandCmdCommandbinDebugnet5.0-windows>exit

我有这段文字,我想从这段文字中提取时间(我在代码中用*表示(,并将其放入变量中,但鉴于字符串中的字符数未知(例如,前三行的字符数不是固定的(,我该怎么做呢

沿着这些线的东西会起作用吗(显然,您需要根据字符串内容中的多次**进行扩展(

using System;
using System.Text.RegularExpressions;

public class Program
{
public static void Main()
{   
var mydata = "Reply from 172.217.18.142: bytes=32 **time=90ms** TTL=127";
var pattern = @"**time=(.*)ms**";

Regex r = new Regex(pattern, RegexOptions.IgnoreCase);      

Match m = r.Match(mydata);
if (m.Success) 
{
Console.WriteLine(m.Groups[1]); // will write '90'
}
}
}

您可以使用正则表达式。例如:

var matches = Regex.Matches(yourString, @"time=d+ms");
foreach(var match in matches)
Console.WriteLine(match);

尝试以下操作:

using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:temptest.txt";
static void Main(string[] args)
{
string input = File.ReadAllText(FILENAME);
StringReader reader = new StringReader(input);
string line = "";
string pattern = @"time=(?'time'd+)";
while((line = reader.ReadLine()) != null)
{
if (line.StartsWith("Reply from"))
{
Match match = Regex.Match(line,pattern);
Console.WriteLine(match.Groups["time"].Value);
}
}
Console.ReadLine();
}
}
}

最新更新