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

本文关键字:文件 获取 文本 正则表达式 何使用 分隔 | 更新日期: 2023-09-27 18:36:52

我有一个SQL脚本,如下所示,用于用一些数据填充数据库表。然后,我在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 正则表达式会为我找到插入参数的值,并且工作正常。(注意,我已使用 ' 个字符更新了 SQL 文件,以显示文件的布局以及读入时它在字符串变量中的存储方式)。请注意,在My_Message值中可以有","和"'"大小写。但是,每个参数的末尾都可以由",'"唯一标识,但我无法让它在正则表达式中工作,并且 String.Split() 只能使用 1 个字符。

列表包含发现的每个匹配项的每个案例,因为我在 SQL 脚本中有 50 多个条目,因此我需要将每个插入语句中的每个单独的 ID、标题和消息拆分为嵌套在循环中的 3 个独立变量。

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

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

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

您可以将正则表达式选项设置为多行匹配数据,这意味着正则表达式将匹配带有行尾而不是字符串末尾的美元符号 $。代码如下:

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;
}