在文本文件中搜索字符串并在 C# 中返回一些字符串

Searching for string in a Text file and returning some string in c#

如何解析文本行:

File.txt:

n:96 pts:341998 pts_time:3.79998 pos:-1 fmt:yuvj420p sar:12/11

并且只获取出现在pts_time之后的时间值。

Expected Output :

3.79998

如何获得预期的输出?? 非常感谢任何帮助。

n:96 pts:341998 pts_time:3.79998 pos:-1 fmt:yuvj420p sar:12/11 拆分为 Space。

string[] lineParts = line.Split(" ".ToCharArray());

获取匹配pts_time键的数组元素。

string ptsTime = lineParts.First(p => p.StartsWith("pts_time")); // pts_time:3.79998

ptsTime 拆分为 :

string ptsTimeValue = ptsTime.Split(':')[1]; // 3.79998

break之前添加:

line = line.Substring(line.IndexOf("pts_time:")).Split(new char[] {':', ' '})[1];

像这样:

private string GetTimeFromFile(string fileName, int searchIndex) {
    //string found = string.Empty;
    string line;
    using (StreamReader file = new StreamReader(fileName)) {
        while ((line = file.ReadLine()) != null) {
            if (line.Contains(string.Format("n:" + searchIndex))) {
                line = line.Substring(line.IndexOf("pts_time:")).Split(':')[1];
                break;
            }
        }
    }
    return line;
}

使用正则表达式提取您需要的信息可以很容易地处理这个问题。您可以构建一个模式来匹配您要查找的行并提取特定信息,如下所示:

string pattern = string.Format("^n:{0}\s.+\spts_time:([\d.]+)\s", searchIndex);

^n:{0}\s 部分将明确识别您之后的行,您可以从捕获的 ([\d.]+).

中提取相关数据

这样使用:

private string GetTimeFromFile(string fileName, int searchIndex)
{
    string pattern = string.Format("^n:{0}\s.+\spts_time:([\d.]+)\s", searchIndex);
    Regex re = new Regex(pattern);
    using (var file = File.OpenText(fileName))
    {
        string line;
        while ((line = file.ReadLine()) != null)
        {
            var m = re.Match(line);
            if (m.Success)
                return m.Groups[1];
        }
    }
    return null;
}

另一个可能对你以后有帮助的正则表达式是这个:

(?:(?<n>\w+):(?<v>\S+))

这将匹配行中的所有 name/value 对,给出多个匹配结果。使用一点 LINQ,您可以轻松地将结果转换为有用的集合,如下所示:

var re = new Regex(@"(?:(?<n>\w+):(?<v>\S+))");
var lineData = 
    // Get all matching terms in the source line
    re.Matches(line)
    // Convert to an enumerable we can use Select on
    .OfType<Match>()
    // Get the key/value out as a KeyValuePair
    .Select(r => new KeyValuePair<string, string>(r.Groups["n"].Value, r.Groups["v"].Value))
    // convert results to a Dictionary<string, string>
    .ToDictionary(kv => kv.Key, kv => kv.Value);

我选择 Dictionary<string, string> 作为输出,但您可以使用您喜欢的任何集合类型。一旦值被分离出来,你就可以将它们提供给工厂方法来创建一个代表行数据的 class 的实例,然后在 solid classes.

上执行所有操作

无论哪种方式,如果您使用它,请确保您了解正则表达式的作用及其原因。当它们出错时,调试起来可能很棘手。关于这个有一个old joke,我不会在这里重复。