python - 在正则表达式中跳过匹配
问题描述
我正在尝试从文本中提取一些数值。跳过是基于匹配的文本完成的。例如 :
Input Text -
ABC Company Export Items 4 Bought by XYZ Amount 400.00 with GST# 36479 GST percentage is 20%.
OR
ABC Company Export Items 4 Bought by XYZ Amount 400.00 with GST Reg No. 36479 GST% is 20%.
OR
ABC Company Export Items 4 Bought by XYZ Amount 400.00 with GST Reg# 36479 GST% is 20%.
Output Text -
Amount 400.00
GST 36479
GST 20%
要点是输入文本可以是任何格式,但输出文本应该相同。相同的一件事是 GST 编号将是非十进制数字,GST 百分比将是数字后跟“%”符号,金额将采用十进制形式。
我试过但无法在 GST 之后跳过非数字值。请帮忙。
我尝试了什么:
pattern = re.compile(r"\b(?<=GST).\D(\d+)")
解决方案
您可以使用
\bAmount\s*(?P<amount>\d+(?:\.\d+)?).*?\bGST\D*(?P<gst_id>\d+(?:\.\d+)?).*?\bGST\D*(?P<gst_prcnt>\d+(?:\.\d+)?%)
请参阅正则表达式演示。详情:
\bAmount\s*
- 一个完整的单词Amount
和零个或多个空格(?P<amount>\d+(?:\.\d+)?)
- 组“金额”:一位或多位数字,然后是一位或多位数字的可选.
序列.*?
- 一些文本(不包括空格)\bGST
- 一个字GST
\D*
-除数字以外的零个或多个字符(?P<gst_id>\d+(?:\.\d+)?)
- 组“gst_id”:一个或多个数字,然后是一个或多个数字的可选.
序列.*?
- 一些文本(不包括空格)\bGST\D*
- 一个单词GST
,然后是零个或多个数字以外的字符(?P<gst_prcnt>\d+(?:\.\d+)?%)
- 组“gst_prcnt”:一个或多个数字,然后是一个或多个数字的可选序列.
,然后是一个%
字符。
请参阅Python 演示:
import re
pattern = r"\bAmount\s*(?P<amount>\d+(?:\.\d+)?).*?\bGST\D*(?P<gst_id>\d+(?:\.\d+)?).*?\bGST\D*(?P<gst_prcnt>\d+(?:\.\d+)?%)"
texts = ["ABC Company Export Items 4 Bought by XYZ Amount 400.00 with GST# 36479 GST percentage is 20%.",
"ABC Company Export Items 4 Bought by XYZ Amount 400.00 with GST Reg No. 36479 GST% is 20%.",
"ABC Company Export Items 4 Bought by XYZ Amount 400.00 with GST Reg# 36479 GST% is 20%."]
for text in texts:
m = re.search(pattern, text)
if m:
print(m.groupdict())
输出:
{'amount': '400.00', 'gst_id': '36479', 'gst_prcnt': '20%'}
{'amount': '400.00', 'gst_id': '36479', 'gst_prcnt': '20%'}
{'amount': '400.00', 'gst_id': '36479', 'gst_prcnt': '20%'}
推荐阅读
- powershell - 无法使用 Keyvault Secrets 进行域加入
- c - 二叉搜索树中的分段错误(核心转储)
- php - Magento 2 在下订单和重定向到购物车时出现致命错误
- google-cloud-platform - 监控谷歌发布订阅
- angular - Angular AUTO alert-dismissible 不起作用
- python - Keras - VGG 微调模型给出错误的预测
- swift-package-manager - 快速包管理器没有找到 KituraNet
- maven - Maven 使用 Kuali S3 Wagon - 如何将 AWS 凭证移动到 pom.xml?
- python - 设置 pd.to_datetime 的格式
- typescript - Algolia 多关键字搜索