我有一个文本文件,其中包含证券名称、金额和投资组合的百分比。我试图弄清楚如何使用正则表达式来区分公司。我有一个原始的解决方案,允许我 .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/