如何限制正则表达式中出现的某些字符

2024-09-25 00:31:46 发布

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

我知道题目可能不清楚,所以我要更具体地描述我的问题。你知道吗

这里有两个字符串:

  1. “基金资产”

  2. “基金寻求通过至少投资其总资产的80%来实现其投资目标”

我的目标是第一个字符串,因此我使用以下正则表达式代码来获取它:

r'fund+.+asset+'

我之所以在“fund+”和“asset+”之间使用“.+”,是因为在其他情况下,“fund”和“asset”之间可能有额外的词,例如“fund total asset”。所以我必须用“.+”来确保我能找到所有可能的目标。你知道吗

然而,第二根绳子,也会被抓住,显然不是我的目标。所以我想把字符数限制在‘基金’和‘资产’之间。你知道吗

伪代码如下:

r'fund+(.+<=6)asset+'

因此,我将“fund”和“asset”之间的字符数限制为不超过6个。你知道吗

regex能做到吗?谢谢你的帮助!:)


Tags: 字符串代码目标基金情况资产asset字符
2条回答

您可以使用^{} operator

r'fund.{1,8}assets'

在“基金”和“资产”之间匹配1到8个任意字符。你知道吗

下面是一个演示:http://refiddle.com/refiddles/56d65e8b75622d6956086500

curly braces检查重复次数:

{m,n} Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as many repetitions as possible. For example, a{3,5} will match from 3 to 5 'a' characters. Omitting m specifies a lower bound of zero, and omitting n specifies an infinite upper bound. As an example, a{4,}b will match aaaab or a thousand 'a' characters followed by a b, but not aaab. The comma may not be omitted or the modifier would be confused with the previously described form.

fund.{1,7}assets

匹配fund assetsfund total assets,但不匹配fund seeks to achieve its investment objective by investing at least 80% of its total assets

>>> re.search(r'fund.{1,7}assets', 'fund assets')
<_sre.SRE_Match object at 0x107951098>
>>> re.search(r'fund.{1,7}assets', 'fund total assets')
<_sre.SRE_Match object at 0x107951030>
>>> re.search(r'fund.{1,7}assets', 'fund seeks to achieve its investment objective by investing at least 80% of its total assets')
>>> 

7用于fund total assets示例-total长度为5个字符加上单词周围的两个空格。你知道吗

相关问题 更多 >