Python证券正则表达式

2024-10-01 07:45:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件,包含安全名称,$金额,和%的投资组合。我正在想办法用regex把公司分开。我有一个原始的解决方案,允许我.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%"]

Tags: 名称公司解决方案金额regexincplcseries
2条回答

在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%']

最初的问题是$锚点使regex只在行的末尾匹配。但是,删除$仍然会将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

Python的工作解决方案,命名组:https://regex101.com/r/sqkFaN/2

(?P<item>(?P<name>.*?)\$(?P<usd>[\d,\.]*?%))

在我提供的链接中,您可以看到更改实时生效,侧边栏提供了所用语法的解释。你知道吗

相关问题 更多 >