我需要的是测试每个日期分组的每一行,并计算其中找到的某个模式的计数。在这个例子中查找并计算" D;"每个日期
样品
My expected output to be displayed into textbox
01 - 3
02 - 0
3 - 4
现在,我已经开始只是读取文本文件显示文本文件中的行数。
protected void btnRead_Click(object sender, EventArgs e)
{
string text = String.Empty;
int i = 0;
using (StreamReader stRead = new StreamReader(FileUpload1.PostedFile.InputStream))
{
//to write textfile content
while (!stRead.EndOfStream)
{
//ListBox1.Items.Add(stRead.ReadLine());
text += stRead.ReadLine() + Environment.NewLine;
i++;
}
}
TextBox1.Text = text;
//Label1.Text = i.ToString();
Label1.Text = this.TextBox1.Text.Split(new Char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length.ToString();
//populateListBox();
}
关于如何开始这个的简单想法将是一个很大的帮助。感谢
答案 0 :(得分:2)
您可以使用Regex
string test = "D; sjhjsd D; sdsdjks D;";
MatchCollection collection = Regex.Matches(test, @"[D;]+");
var x= collection.Count;
结果:3
此编辑显示如何实现上述Regex
以计算每条已知行
protected void btnRead_Click(object sender, EventArgs e)
{
string text = String.Empty;
int i = 0;
int countedChars;
using (StreamReader stRead = new StreamReader(FileUpload1.PostedFile.InputStream))
{
//to write textfile content
while (!stRead.EndOfStream)
{
var readedLine = stRead.ReadLine()
//ListBox1.Items.Add(readedLine );
if (!string.IsNullOrWhiteSpace(readedLine))
{
MatchCollection collection = Regex.Matches(readedLine, @"D;");
countedChars = collection.Count;
text += readedLine.Substring(0, readedLine.IndexOf(' ')) +" - "+countedChars + Environment.NewLine;
}
i++;
}
}
TextBox1.Text = text;
//Label1.Text = i.ToString();
Label1.Text = this.TextBox1.Text.Split(new Char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length.ToString();
//populateListBox();
}
答案 1 :(得分:1)
使用正则表达式:
MatchCollection mc = Regex.Matches(lineread, "D;");
int count = mc.Count;
整个功能将是这样的:
string[] lines = System.IO.File.ReadAllLines("file.txt");
string result = "";
for(int i=0;i<lines.Length;i++)
{
MatchCollection mc = Regex.Matches(lines[i], "D;");
result+= string.Format("{0} - {1}\r\n", i+1, mc.Count);
}
答案 2 :(得分:1)
试试这个:
var pattern = "D";
while (!stRead.EndOfStream)
{
line+= stRead.ReadLine();
if (!string.IsNullOrEmpty(line))
{
var matches = Regex.Matches(line, @"^\d{4}-\d{2}-(\d{2,3})\sproductkey=([\w;]*)");
if (matches.Count > 0)
{
var day = matches[0].Groups[1].Value;
var productKey = matches[0].Groups[2].Value;
var count = Regex.Matches(productKey, pattern).Count;
text += string.Format("{0} - {1}{2}", day, count, Environment.NewLine);
}
}
}
TextBox1.Text = text;
输出:
01 - 3
02 - 0
03 - 4
您可以根据需要更改模式和日期。例如:
2016-12-07 productkey = D; D; D; 0; 0
2016-12-11 productkey = Y; Y; Y; 0; 0
2016-12-25 productkey = D; D; D; D; 0
var pattern = "Y";
输出:
07 - 0
11 - 3
25 - 0