我有一個如下的SQL腳本,用於用一些數據填充數據庫表。 然後,我在VS2010中使用C#中的StreamReader讀取此文件。我想知道的是,一旦我把這個文件作爲字符串讀入,我怎樣才能將每個單獨的參數分成一個子字符串?如何使用正則表達式從 n分隔的文本文件中獲取特定值?
那麼理想情況下,我想要將每個VALUE參數讀入它自己的獨立子字符串中,以便我可以處理它。
SQL腳本:
...
INSERT INTO [dbo].[My_Table] (\n My_ID, \n My_Title, \n My_Message \n) VALUES (\n 40, \n 'Hello, This is the message title', \n 'Hello, This is \n the message body' \n)
INSERT INTO [dbo].[My_Table] (\n My_ID, \n My_Title, \n My_Message \n) VALUES (\n 41, \n 'Hello again, This is another message title', \n 'Hello again, This is \n another message body' \n)
我正在調試這一點,並嘗試了幾種不同的方法,一個使用String.Split(),另一個使用正則表達式的方法。
這裏是我的C#代碼:
// this is to find the VALUES parameters in the SQL file
private static readonly Regex matchValues = new Regex(@".*?VALUES.*?\((.*?)\)",
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant
|RegexOptions.Singleline);
// fileText is the string object containing the raw text read in from the SQL file
public static string FindMatches(string fileText)
{
List<Match> matches = matchValues.Matches(fileText).Cast<Match>().ToList();
foreach (Match match in matches)
{
string value = match.Groups[1].Value;
string pattern = @"^,$";
// do work
string[] delimiters = new string[] { ",\n" };
string[] splitGroup = value.Split(delimiters, StringSplitOptions.None);
string[] split = Regex.Split(value, pattern);
}
}
所以,如果我可以簡單介紹一下該代碼,matchValues正則表達式是找到我的值插入參數,這是工作的罰款。 (注意,我用\ n字符更新了SQL文件以顯示文件的佈局以及在讀入時它如何存儲在字符串變量中)。請注意,在My_Message值中可能有','和'\ n'的情況。但是,每個參數的末尾可以用',\ n'唯一標識,但是我無法在正則表達式中工作,並且String.Split()只能使用1個字符。
該列表包含發現的每個匹配的每種情況,因爲我在SQL腳本中有超過50個條目,所以我需要將每個插入語句中的每個單獨ID,標題和消息拆分爲3個嵌套循環。
目前splitGroup []字符串對象返回太多子字符串,因爲我們在參數值中有新行,並且使用Regex的split []字符串對象只是將其全部作爲一個字符串返回。
我希望這個更新的信息是有幫助的。
在此先感謝!
爲什麼正則表達式,而不是'string.Split()'? –
嗨@Jeremy,我已經更新了我的問題,以更具體一點,並解釋了爲什麼string.Split()目前不適用於我。謝謝 – user1451813