regex - 正则表达式获取特定匹配词后的词
问题描述
我正在尝试从一些发票中提取美元金额。我需要匹配在单词“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”一词之后拉出所有内容。我只想要下一个词。
解决方案
解释在正则表达式模式中。
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);
推荐阅读
- maven - 在 Maven 多模块项目中,如何从另一个模块获取一个模块的 buildVersion?
- c# - 如何在 Asp.Net MVC 5.x 中使用条件序列化?
- javafx - 程序运行时,如何使 MediaView 具有相同的布局边界的高度和宽度?
- ios - UIApplication.OpenURLOptionsKey.sourceApplication 在 iOS 13 上为零?
- c++ - 我可以在单读/单写队列中用 volatile 替换原子吗?
- javascript - 我收到“参考错误:未定义按钮”错误
- java - 无法使用自定义反序列化器反序列化 JSON 对象
- swift - 功能只是快速读取最高值
- c++ - 从多个源构造一个对象,包括对象向量
- assembly - 在 MIPS 中将用户输入的十六进制字符串转换为二进制的更好方法是什么?