使用c# regex从字符串中获取多个数据

本文关键字:获取 数据 字符串 regex 使用 | 更新日期: 2023-09-27 18:01:47

下面是日志文件中的一行示例,我已经使用了一段时间了:

5/21/2015 11:55:56 PM | Batch 6|386/767|50.33 %|CH2M-R|Processed NXRMN5...Checking refundable and non-refundable fares. Traditional Booking. Inside ticketing window. Minimum Savings Required: $131.00. Actual Savings: $257.18. Savings found: $257.18 (11.55 %). Savings were previously found.

在这个文件中,我有需要捕获的类别:首先是日期和时间,接下来是定位器(NXRMN5),发现的储蓄和百分比(如果有的话),这一行是$257.18 11.5%。

在控制台中,我希望它看起来像这样:

Date:  5/21/2015 11:55:56 PM 
Locator: NXRMN5
Dollar Savings: $257.18 
Percent Savings: 11.55 %

下面是一些我已经写了很长时间的代码:

foreach (string line in gdsLines)
        {
            Match m = Regex.Match(line, @"Savings's+found:'s*'$(?<savings>'d+'.'d+)'s*'('s*(?<percent>'d+'.'d+)'s*%");
            if (m.Success)
            {
                decimal gdsNumberSavings = decimal.Parse(m.Groups["savings"].Value, CultureInfo.InvariantCulture);
                decimal gdsNumberPercent = decimal.Parse(m.Groups["percent"].Value, CultureInfo.InvariantCulture);
                Console.WriteLine("Dollar Savings: $"  + gdsNumberSavings + " Percent Savings: " + gdsNumberPercent + " % " + "'n");
                gdsTotalSavings += gdsNumberSavings;
                gdsTotalPercentage += gdsNumberPercent;
            }
        } 

我提供的这段代码接受我创建的正则表达式,然后将找到的节省量和百分比放在一起,然后在控制台中打印值。不用担心gdsTotal变量。主要关注的是正则表达式。为了添加我需要的其他元素,我是否需要创建另一个正则表达式,或者我可以直接添加到它上面?无论哪种方式,有人可以帮助我在形成这个正则表达式?任何帮助都会非常感激!

使用c# regex从字符串中获取多个数据

我建议这样做:

  1. Date仅通过使用|拆分字符串并获得第一个元素
  2. 来提取。
  3. 定位符是用正则表达式捕获的。

代码如下:

string line = "5/21/2015 11:55:56 PM | Batch 6|386/767|50.33 %|CH2M-R|Processed NXRMN5...Checking refundable and non-refundable fares. Traditional Booking. Inside ticketing window. Minimum Savings Required: $131.00. Actual Savings: $257.18. Savings found: $257.18 (11.55 %). Savings were previously found.";
string date = line.Split('|').Take(1).FirstOrDefault().Trim();
Match m = Regex.Match(line, @"Processed's+(?<locator>[^.]+)'.{3}.*?Savings's+found:'s*'$(?<savings>'d+'.'d+)'s*'('s*(?<percent>'d+'.'d+)'s*%");
if (m.Success)
{
     decimal gdsNumberSavings = decimal.Parse(m.Groups["savings"].Value, CultureInfo.InvariantCulture);
     decimal gdsNumberPercent = decimal.Parse(m.Groups["percent"].Value, CultureInfo.InvariantCulture);
     string locator = m.Groups["locator"].Value;
     Console.WriteLine("Date:  " + date + ", Locator: " + locator + "Dollar Savings: $" + gdsNumberSavings + " Percent Savings: " + gdsNumberPercent + " % " + "'n");
     gdsTotalSavings += gdsNumberSavings;
     gdsTotalPercentage += gdsNumberPercent;
}
输出:

Date:  5/21/2015 11:55:56 PM, Locator: NXRMN5Dollar Savings: $257,18 Percent Savings: 11,55 % 

或者,您可以在单个regex中使用相同的逻辑:

Match m = Regex.Match(line, @"^(?<date>[^|]+)'|.*Processed's+(?<locator>[^.]+)'.{3}.*?Savings's+found:'s*'$(?<savings>'d+'.'d+)'s*'('s*(?<percent>'d+'.'d+)'s*%");

if块内:

string date = m.Groups["date"].Value.Trim();