Saturday, May 11, 2013

How to validate data using regex?

the code below should work



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static string testData = "<script type=\"text/javascript\">var d=[];" +
"d=[['1','1','Category 1','1','0','201304290300','Product A','Description A','0','0','0','0','0','0','825956','1','N','0','0','0','0','0.5',,'0.87','0.82',,,'5','14','7500','3','1','98','90','0','1','3','5',,'99','89',,,'1','6',,'40','340','99','|',,'2','2','0','0',,'79','890',,,'6','4','0','1','1','8.2','9.2','0','1','8','7',,'2.9','2.15','3.7','|',,,,,,,,,'7','0','0']," +
"[,,,,,,,,,,,,,,,,,,'0','1','0','0',,'7.9','0.84',,,'5','3','2.5','2.5',,'7.9','8.7',,,,,,,,,,,,,,,,,,'2','15','0.25','0.5',,'0.73','63',,,'6','16','1.25','1.5',,'0.79','0.69',,,,,,,,,,,,,,,,,,'7','0','1']," +
"[,,,,,,,,,,,,,,,,,,'0','17','0.5','0.5',,'0.69','6.4',,,'5','18','3.0','3',,'0.76','0.68',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,'7','0','2']," +
"['2','2','Category 2','848352','0','201304290300','Product B','Description B','0','0','0','0','0','0',,'1','N','0','0','1','1.25','1.5',,'0.95','8900',,,'5','3','5.25','5.5',,'100','900',,,,,,,,,,'1','6',,'45','55','402','|',,'2','2','5000','5',,'1','84',,,'6','4','250','25',,'90','8600',,,'8','7',,'97','32','333','|',,,,,,,,,'2','0','3']," +
"['3','3','Category 2','841462','0','201304290300','Product C','Description C','0','0','0','0','0','0',,'1','N','0','0','1','1.5','1.5',,'89','73',,,'5','3','12','12',,'85','97',,,'3','5',,'93','93',,,,,,,,,,,'2','2','0.5','0.5',,'84','0',,,'6','4','55','55',,'0','99',,,,,,,,,,,,,,,,,,'1','0','13']];show(d);</script>";
static void Main(string[] args)
{
string pattern = "";
Regex expr;
MatchCollection matches;
string bracketExpr;
List<List<string>> table = new List<List<string>>();
//put beginning of string in seperate group
pattern = @"(.*;d=\[)" +
//put open close brackets into own group
@"(.*)" +
//put the last bracket and everything following into seperate group
@"(\][^\[\]]*)$";
expr = new Regex(pattern);
matches = expr.Matches(testData);
bracketExpr = matches[0].Groups[2].ToString();
pattern = @"(?'Open'\[)([^\[\]]*)+(?'Close-Open'\])";
expr = new Regex(pattern);
matches = expr.Matches(bracketExpr);
foreach (Match match in matches)
{
string data = match.ToString();
//replace leading and trailing brackets with nothing
data = data.Replace("[", "");
data = data.Replace("]", "");
//remove single quotes
data = data.Replace("'", "");
string[] fields = data.Split(',');
List<string> newRow = new List<string>();
newRow.AddRange(fields);
table.Add(newRow);
}
}
}
}





jdweng


No comments:

Post a Comment