我有一个文本文件,其中包含安全名称、$ and和投资组合的%。我想弄清楚如何用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%"]发布于 2017-08-08 20:34:50
在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之后的%中的两个条目。
为了解决这个问题,regex会查找一个$,然后再查找一个%,并将%中的所有内容作为一个条目进行处理。这种模式适用于您给出的示例,但是,当然,我不知道它对所有数据是否成立。
编辑 regex的工作方式如下:
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发布于 2017-08-08 20:46:22
使用命名组的Python工作解决方案:https://regex101.com/r/sqkFaN/2
(?P<item>(?P<name>.*?)\$(?P<usd>[\d,\.]*?%))在我提供的链接中,您可以看到更改具有实时效果,侧栏为使用的语法提供了解释。
https://stackoverflow.com/questions/45577481
复制相似问题