繁体   English   中英

如何使用正则表达式从以\\\\分隔的文本文件中获取特定值?

[英]How can I use a Regex to get specific values from a text file delimitted by ,\n?

我有一个如下的SQL脚本,用于用一些数据填充db表。 然后,我在VS2010中使用C#中的StreamReader读取此文件。 我想知道的是,一旦我以字符串形式读取了此文件,如何将每个参数拆分为一个子字符串?

因此,理想情况下,我想要将每个单独的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(),另一种使用Regex方法。

这是我的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 Regex可以为我找到insert参数的值,并且可以正常工作。 (请注意,我已经用\\ n字符更新了SQL文件,以显示文件的布局以及读入时如何存储在字符串变量中)。 请注意,在My_Message值中可以有','和'\\ n'大小写。 但是,每个参数的末尾都可以由',\\ n'唯一标识,但是我无法在Regex和String.Split()中使用它,只能使用1个字符。

由于我在SQL脚本中有50多个条目,因此List包含发现的每个匹配的每种情况,因此我需要将每个Insert语句中的每个ID,Title和Message拆分为三个单独的变量,这些变量嵌套在循环中。

当前,由于我们在参数值中包含新行,splitGroup []字符串对象返回了太多的子字符串,而使用Regex的split []字符串对象只是将其全部返回为一个字符串。

我希望此更新的信息对您有所帮助。
提前致谢!

您可以将RegexOptions设置为与数据多行匹配,这意味着regex将使美元符号$与行尾而不是字符串尾匹配。 这是代码:

string strRegex = @"^Regex Test";
RegexOptions myRegexOptions = RegexOptions.Multiline;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strTargetString = @"Regex Test for stackoverflow.";

foreach (Match myMatch in myRegex.Matches(strTargetString))
{
  if (myMatch.Success)
  {
    // Add your code here
  }
}

您也可以使用String.Split

var inserts = File.ReadLines(path)
         .Where(l => l.IndexOf("VALUES (") > -1)
         .Select(l => new
         {
             SQL = l,
             Params = l.Substring(l.IndexOf("VALUES (") + 8)
                       .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
         });
foreach (var insert in inserts)
{
    String sql = insert.SQL;
    String[] parameter = insert.Params;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM