Reputation:
Here is a text: string txt holds this value.
CREATE TABLE table_name1 ( column_name11231 data_type, column_name232 data_type, column_name3 data_type, .... )
CREATE TABLE table_name2 ( column_name1 data_type, column_name2 data_type, column_name3 data_type, .... )
CREATE TABLE table_name3 ( column_name1231 data_type, column_name2 data_type, column_name3 data_type, .... )
CREATE TABLE table_name4 ( column_name1231 data_type, column_name1232 data_type, column_name1233 data_type, .... )
this is a sample. i will read it from a text file. then i just want to take each CREATE TABLE command in a string array. how could i take it? I have tried split and substring. but that was foolish. I have done it with a silly and uneffective way.
here is it:
string[] totalSp = Regex.Split(txt, "CREATE TABLE");
string[] output = new string[totalSp.Length-1];
for (int i = 1; i < totalSp.Length; i++ )
{
output[i - 1] = "CREATE TABLE " + totalSp[i].Replace("\r\n", "");
}
this give me the desired output. but i now this is poor coding. cannot I do it any simplier way?
Upvotes: 1
Views: 73
Reputation: 56536
You can use this regex to find the statements, as long as you're not going to have much variation in the input.
var matches = Regex.Matches(txt, @"^CREATE TABLE .+", RegexOptions.Multiline);
string[] myArray = matches.Cast<Match>().Select(x => x.ToString()).ToArray();
Upvotes: 1
Reputation: 203817
You can use File.ReadLines
to get the lines, and it's easy enough to filter the empty lines out without regexes.
var commands = File.ReadLines("filename.txt")
.Where(line => !string.IsNullOrEmpty(line))
.ToArray();
If there are other commands in the file besides create table
then you can add a simple filter for that too. Just add the below command after the other filter:
.Where(line => line.StartsWith("CREATE TABLE"))
Upvotes: 0