Reputation: 11010
Here i am writing into a text file..I am searching for a key word Raiserror
in a sql file and if that keyword exist i have to write that line..
It is writing like
LineNo : 66 : raiserror ('Sequence number cannot be blank',16,1)
But i need to write only
LineNo : 66 : Sequence number cannot be blank
Is this possible..If so how to trim.. Here is my code
while ((line = file.ReadLine()) != null)
{
if (line.IndexOf("Raiseerror", StringComparison.CurrentCultureIgnoreCase) != -1)
{
dest.WriteLine("LineNo : " + counter.ToString() + " : " + " " + line.TrimStart());
}
counter++;
}
file.BaseStream.Seek(0, SeekOrigin.Begin);
counter = 1;
Any Suggestion?
Upvotes: 3
Views: 179
Reputation: 36339
easiest is probably to use a capturing regex expression. You should be able to do something like this:
string pattern = @"raiserror \(\'(?<errortext>.+)\'";
Regex exp = new Regex(pattern);
Match match = exp.Match(line);
string errorText = match.Groups["errortext"].Value;
I was a little verbose there, creating more variables than strictly needed, but that should do it. You might need to tinker w/ the regex pattern a bit for your specific case, mine was the simplest one that worked for the sample line you gave.
You could likewise have multiple capture groups if there are several text features you want to extract from each line (e.g. line number, date, etc).
Upvotes: 2
Reputation: 5419
if the startup is always the same, asin LineNo : 66 : and the error is always within ' you can use this:
private string GetText(string text)
{
return string.Format("{0} {1}", text.Substring(0, text.LastIndexOf(":") + 1), text.Substring(text.IndexOf("'") + 1, (text.LastIndexOf("'") - text.IndexOf("'")) - 1));
}
var text = GetText("LineNo : 66 : raiserror ('Sequence number cannot be blank',16,1)");
this returns "LineNo : 66 : Sequence number cannot be blank"
[edit]
text.Substring(text.IndexOf("'") + 1, (text.LastIndexOf("'") - text.IndexOf("'")) - 1)
does what you want.
You'll have to build the rest around it yourself ofcourse!
Upvotes: 1
Reputation: 17808
I'm not 100% sure what your asking... why add all that whitespace if you want to trim the line? I will remove the answer if I am misreading the question.
var logLine = "LineNo : " + counter.ToString() + " : " + " ";
dest.WriteLine(logLine.Trim());
Upvotes: 0
Reputation: 23266
Try to use this
int errorIndex = line.IndexOf("Raiseerror", StringComparison.CurrentCultureIgnoreCase)
if (errorIndex != -1)
{
int start = line.IndexOf('\'', errorIndex) + 1;
int finish = line.IndexOf('\'', start);
dest.WriteLine("LineNo : " + counter.ToString() + " : " + " " + line.Substring(start,finish - start));
}
Upvotes: 2