用于证券的 Python 正则表达式

标签 python regex finance

我有一个文本文件,其中包含证券名称、金额和投资组合的百分比。我试图弄清楚如何使用正则表达式来区分公司。我有一个原始的解决方案,允许我 .split('%') 然后创建我需要的 3 个变量,但我发现一些证券在其中包含 %名称,因此解决方案不充分。

字符串示例:

Pinterest, Inc. Series F, 8.00%$24,808,9320.022%ResMed,Inc.$23,495,3260.021%Eaton Corp. PLC$53,087,8430.047%

当前正则表达式

[a-zA-Z0-9,$.\s]+[.0-9%]$

我当前的正则表达式只能找到最后一家公司。例如,伊顿公司 PLC$53,087,8430.047%

关于如何找到公司的每个实例,有什么帮助吗?

所需的解决方案

["Pinterest, Inc. Series F, 8.00%$24,808,9320.022%","ResMed,Inc.$23,495,3260.021%","Eaton Corp. PLC$53,087,8430.047%"]

最佳答案

在 Python 3 中:

import re
p = re.compile(r'[^$]+\$[^%]+%')
p.findall('Pinterest, Inc. Series F, 8.00%$24,808,9320.022%ResMed,Inc.$23,495,3260.021%Eaton Corp. PLC$53,087,8430.047%')

结果:

['Pinterest, Inc. Series F, 8.00%$24,808,9320.022%', 'ResMed,Inc.$23,495,3260.021%', 'Eaton Corp. PLC$53,087,8430.047%']

您最初的问题是 $ anchor 使正则表达式仅在行尾匹配。但是,在 8.00 之后,删除 $ 仍会将 Pinterest 分成 % 处的两个条目。

为了解决这个问题,正则表达式会查找 $,然后查找 %,并通过 % 将所有内容作为入口。该模式适用于您给出的示例,但是,当然,我不知道它是否适用于您的所有数据。

编辑正则表达式的工作方式如下:

r'               Use a raw string so you don't have to double the backslashes
  [^$]+          Look for anything up to the next $
       \$        Match the $ itself (\$ because $ alone means end-of-line)
         [^%]+   Now anything up to the next %
              %  And the % itself
               ' End of the string

关于用于证券的 Python 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45577481/

相关文章:

python - 如何将 Hermite 多项式与随机梯度下降 (SGD) 结合使用?

python - 如何使用 UNICODE 字符串格式化模板中的 JINJA 变量?

python - Pandas 数据框 : how to group by values in a column and create new columns out of grouped values

regex - sed、awk 或 perl 过滤不完整的数据列

金融随机指标的Java实现

r - 在 Quantmod R 中添加多个图表系列

api - 需要一个 API 来查找给定股票代码的完整公司名称

python - Soundcloud API python 与链接分区相关的问题

javascript - JS : How to remove style tags and their content from an HTML string, 使用正则表达式?

javascript - 为什么这个 javascript 正则表达式不匹配第二个和第四个模式?