首页 > 解决方案 > 正则表达式获取特定匹配词后的词

问题描述

我正在尝试从一些发票中提取美元金额。我需要匹配在单词“TOTAL”之后的单词上。此外,total 一词有时可能会在其后出现一个冒号(即Total:)。示例文本示例如下所示:

4 发现信用购买 - c 编号:02353R 总计:40.00援助:1523Q1Q TC:mzQm 40.00 更改 0.00 已售商品总数 = 0 2017 年 12 月 23 日 Ql:38piii 414 9 76 1G6 感谢您购买 KR08ER 现在招聘 - 申请今天!

在上面的示例中,匹配应该是"40.00"

我写的正则表达式语句:

(?<=total)([^\n\r]*)

在“total”一词之后拉出所有内容。我只想要下一个词。

标签: regex

解决方案


解释在正则表达式模式中。

string str = "4 Discover Credit Purchase - c REF#: 02353R TOTAL: 40.00 AID: 1523Q1Q";
string pattern = @"(?ix)       # 'i' means case-insensitive search
                    \b         # Word boundary
                    total      # 'TOTAL' or 'total' or any other combination of cases
                    :?         # Matches colon if it exists
                    \s+        # One or more spaces
                    (\d+\.\d+) # Sought number saved into group
                    \s         # One space";
// The number is in the first group: Groups[1]
Console.WriteLine(Regex.Match(str, pattern).Groups[1].Value);

推荐阅读