从文件C#获取文本

时间:2016-01-18 08:34:18

标签: c#

我正在阅读文本文件行按行,并且我想在检查是否包含特殊字符的行之后获取特殊字符之间的数据。在我的情况下,我想检查行是否包含<#Tag()>,如果它包含然后在()之间获取字符串,即行有<#Tag(param1)>然后它应该返回param1

但问题是行可能包含多个<#Tag()> 例如,Line有 - <#Tag(value1)> <#Tag(value2)> <#Tag(value3)> 然后它应首先返回value1然后value2然后value3

string contents = File.ReadAllText(@"D:\Report Format.txt");
int start = contents.IndexOf("Header") + "Header".Length;
int end = contents.IndexOf("Data") - "Header".Length;
int length = end - start;
string headerData = contents.Substring(start, length);
headerData = headerData.Trim(' ', '-');
MessageBox.Show(headerData);
using (StringReader reader = new StringReader(headerData))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        if (line.Contains("<#Tag"))
        {
            string input = line;
            string output = input.Split('<', '>')[1];
            MessageBox.Show(output);
            Globals.Tags.SystemTagDateTime.Read();
            string newoutput =  Globals.Tags.SystemTagDateTime.Value.ToString();
            input = input.Replace(output, newoutput);
            input = Regex.Replace(input, "<", "");
            input = Regex.Replace(input, ">", "");
            MessageBox.Show(input);
        }
    }
}

4 个答案:

答案 0 :(得分:3)

尝试以下

var matches = Regex.Matches(line, @"(?<=\<\#Tag\()\w+(?=\)\>)")
foreach (Match match in matches)
  MessageBox.Show(match.Value);

如果您想完成评论中描述的上下文,请尝试以下操作。

  var line = "<#Tag(value1)> <#Tag(value2)>  <#Tag(value3)>";
  var matches = Regex.Matches(line, @"(?<=\<\#Tag\()\w+(?=\)\>)");
  //use matches in your case to find values. i assume 10, 20 , 30
  var values = new Dictionary<string, int>() { { "value1", 10 }, { "value2", 20 }, { "value3", 30 } };
  const string fullMatchRegexTemplate = @"\<\#Tag\({0}\)\>";
  foreach (var value in values)
    Regex.Replace(line, string.Format(fullMatchRegexTemplate, value.Key), value.Value.ToString());

答案 1 :(得分:0)

你可以用正则表达式做这个(我会在一个上面工作) - 但作为一个简单的快捷方式就是这样做:

var tags  = line.Split(new string[] { "<#Tag" }, StringSplitOptions.None);
foreach(var tag in tags)
{
 //now parse each one
}

我看到tchelidze刚发布的正则表达式看起来很不错,所以我会按照正则表达式推迟答案。

答案 2 :(得分:0)

这可能会为你做到这一点

string tmp = Regex.Replace(n, "[^0-9a-zA-Z]*[Tag]*[^0-9a-zA-Z]", ",");

基本上它匹配所有非字母数字字符。

cascade_validation

另一个可能是

cascade_validation

答案 3 :(得分:0)

您可以在将字符串按常量值<#Tag()>分割后收集它们,如下所示:

string str = "<#Tag(value1)> <#Tag(value2)>  <#Tag(value3)>";
string[] values = str.Split(new string[] { "<#Tag(", ")>" }, StringSplitOptions.RemoveEmptyEntries);

值包含:

value1, value2, value3

在MessageBox中显示结果:

foreach (string val in values) {
    if (!(String.IsNullOrEmpty(val.Trim()))) {
        MessageBox.Show(val);
    }
}

根据您的评论进行编辑:

我可以在一个消息框中显示完整的value1 value2 value3,而不是使用逗号,但间距与

相同
string text = "";
foreach (string val in values) {
    text += val;
}
MessageBox.Show(text);

基于评论: 现在是最后一个查询在消息框中显示之前我想用它们替换它,例如10 20和30

string text = "";
foreach (string val in values) {
   // where val is matching your variable (let's assume you are using dictionary for storing the values)
   // else is white space or other... just add to text var.
   if (yourDictionary.ContainsKey(val)) {
       text += yourDictionary[val];
   } else {
       text += val;
   }
}
MessageBox.Show(text);
相关问题