-1

我正处于紧要关头。我正在阅读一个非分隔的文本文件,并且除了一个细节之外已经成功:我需要在作为员工标识符的字符串行中识别一个 10 位数字,并将其链接到数据库以提取电子邮件并向员工发送电子邮件文件。我没有问题单独提取每个员工的文件(这是一个包含所有员工数据的大型文本文件),但我需要通过电子邮件将这个单独的文件发送给他们。现在,我有一个查询,虽然根本没有优化,但不会导致操作问题,因为它是一个辅助数据库并且几乎没有使用。

 using (var cnn = new SqlConnection(connStr))
        {
            cnn.Open();
            using (var cmd = new SqlCommand("SELECT  EMail from Stubs WHERE CONTAINS (ID, @ID)", cnn))
            {
                cmd.Parameters.AddWithValue("@ID", (line));
                using (var rdr = cmd.ExecuteReader())
                {
                    if (rdr.HasRows)
                    {
                        while (rdr.Read())
                        {
   email = rdr.GetString(0);

                        }
                    }
                }
            }

我正在检查每个读取行并将其与一个字段进行比较。显然这是行不通的,因为字符串总是由以下组成:

Acct              0100001170                              180.18   39,870.80 

我需要在那里提取这 10 位数字 0100001170,并使用提取的值来识别数据库中的列并获取电子邮件地址。

我怎样才能只提取那个数字?可能吗?

4

2 回答 2

1

As Jon Skeet suggested, a regular expression will work for this scenario.

    string id = Regex.Match(line, @"(?<=\s)\d{10}(?=\s)").Value;

What this does is capture a certain part of your input string (line in this case) based on a search pattern. The one I built here, "(?<=\s)\d{10}(?=\s)" comprises of a few confusing-looking elements.

  • (?<=\s) - This is a positive lookbehind for \s, the whitespace character. This will match anything that has whitespace before the string
  • \d - This matches a digit
  • {10} - This says to match the preceeding token (\d in this case) 10 times.
  • (?=\s) - Similar to the first item this looks for whitespace after the string

After the Regex match, you should have a string containing ten numeric digits which is accessed with .Value.

If you find yourself struggling with regular expressions in the future, I recommend Regexr. It is a web application that allows you to test out regex strings and matching and gives quite good reference for the different tokens.

于 2013-11-14T19:21:03.697 回答
0

如果帐号在每行中的相同位置,这将起作用:

while (rdr.Read())
{
    email = rdr.GetString(0);
    // make sure the string is long enough or you will get an index out of range exception
    if (rdr.GetString().Length() > 29)
    {
        string acctno = rdr.GetString().Substring(19, 10);
        // do something with acctno, maybe cast it to an Int64 if it is numeric
    }
}
于 2013-11-14T19:21:18.157 回答