我有一个包含证券名称、金额和投资组合百分比的文本文件。我想弄清楚如何使用正则表达式来区分公司。我有一个原始的解决方案,允许我 .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%]$
我当前的正则表达式只能找到最后一家公司。例如,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%"]
请您参考如下方法:
在 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 使正则表达式仅匹配行尾。但是,删除 $ 后,Pinterest 仍会在 8.00 之后的 % 处拆分为两个条目。
为了解决这个问题,正则表达式查找 $,然后是 %,然后通过 % 获取所有内容作为入口。该模式适用于您提供的示例,但是,当然,我不知道它是否适用于您的所有数据。
编辑 正则表达式的工作方式如下:
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
