使用正则表达式基于不包括换行符的重复模式进行提取



我有一个字符串如下:

27223525
 
West Food Group B.V.9
 
52608670
 
Westcon
 
Group European Operations Netherlands Branch
 
30221053
 
Westland Infra Netbeheer B.V.
 
27176688
 
Wetransfer  85 B.V.
 
34380998
 
WETRAVEL B.V.
 
70669783

此字符串包含许多换行符,我想明确忽略这些以及所有具有 6 个或更多数字的多位数。我想出了以下正则表达式:

[^nd{6,}].+

这几乎把我带到了那里,因为它返回了所有公司名称,但是在公司名称本身包含换行符的情况下,这些字符将作为两个不同的公司名称返回。例如,Westcon是匹配项,Group European Operations Netherlands Branch也是匹配项。我想调整上面的表达式以确保最终匹配是Westcon European Operations Netherlands Branch。我应该使用哪些正则表达式概念来实现此目的?

编辑

我根据下面的评论尝试了以下内容,但得到了错误的结果

text = 'West Food Group B.V.9n n52608670n nWestconn nGroup European Operations Netherlands Branchn n30221053n nWestland Infra Netbeheer B.V.n n27176688n nWetransfer 85 B.V.n n34380998n nWETRAVEL B.V.n n70669783n nWeWork Companies (International) B.V.n n61501220n nWeWork Netherlands B.V.n n61505439n nWexford Finance B.V.n n27124941n nWFCn-nFood Safety B.V.n n11069471n nWhale Cloud Technology Netherlands B.V.n n63774801n nWHILL Europe B.V.n n72465700n nWhirlpool Nederland B.V.n n20042061n nWhitakern-nTaylor Netherlands B.V.n n66255163n nWhite Oak B.V.n'
re.findall(r'[^nd{6,}](?:(?:[a-zs.]+(n[a-zs.])*)|.+)',text)
我认为

您只需要公司名称。如果是这样,这应该有效。

input = '''27223525
West Food Group B.V.9
52608670
Westcon
Group European Operations Netherlands Branch
30221053
Westland Infra Netbeheer B.V.
27176688
Wetransfer 85 B.V.
34380998
WETRAVEL B.V.
70669783
'''
company_name_regex = re.findall(r'[A-Za-z].*|[A-Za-z].*d{1,5}.*', input)
pprint(company_name_regex)
['West Food Group B.V.9',
 'Westcon',
 'Group European Operations Netherlands Branch',
 'Westland Infra Netbeheer B.V.',
 'Wetransfer 85 B.V.'
 'WETRAVEL B.V.']

这将为没有数字的行创建一个组。

正则表达式:/(?!(d{6,}|n))[a-zA-Z .n]+/g

演示:https://regex101.com/r/MMLGw6/1

假设您的公司名称以字母开头,您可以将此正则表达式与re.M修饰符一起使用:

^[a-zA-Z].*(?:n+[a-zA-Z].*)*(?=n+d{6,}$)

正则表达式演示

在蟒蛇中:

regex = re.compile(r"^[a-zA-Z].*(?:n+[a-zA-Z].*)*(?=n+d{6,}$)", re.M)

这将匹配以 [a-zA-Z] 开头到行尾的行,然后匹配由n分隔的更多行,这些行也以[a-zA-Z]字符开头。

(?=n+d{6,}$)是一个前瞻性断言,以确保我们的公司名称前面有一个换行符和 6+ 位数字。

如果你可以在没有正则表达式的情况下解决这个问题,那么应该在没有正则表达式的情况下解决这个问题:

useful = []
for line in text.split():
    if line.strip() and not line.isdigit():
        useful.append(line)

这应该有效 - 或多或少。 从我的手机回复,所以无法测试。

最新更新