Python-在其他两个特定字符之间的字符串中提取文本?

时间:2018-06-28 02:26:36

标签: python regex zapier

我有各种各样的文本字符串,其中包含用户名,公司名称和电话号码,它们都类似于以下内容:

FirstName LastName (Some Business Name / phoneNumber)
FirstName LastName (Business Name / phoneNumber)
FirstName LastName (BusinessName / differentphoneNumber)
FirstName LastName (Short Name / somephoneNumber)
FirstName LastName (Very Long Business Name / otherphoneNumber)

现实世界中的示例可能如下所示:

David Smith (Best Pool and Spa Supplies / 07438473784)
Bessy McCarthur Jone (Dog Supplies / 0438-343522)

我已经使用此代码提取了名字(如我之前所需要的),并且效果很好:

import re
details = re.findall(r'^[\w+]+', input_data['stripeDescription'])
return {
'firstName': details[0] if details else None\``
}

我该如何去查找方括号“(”和正斜杠“ /”之间的文本,然后检索公司名称?

3 个答案:

答案 0 :(得分:3)

这可能不是一个完美的解决方案,但效果很好:)

s1='David Smith (Best Pool and Spa Supplies / 07438473784)'
sp1=s1.split('(')
sp2=sp1[1].split('/')
print(sp2)

输出:['最佳泳池和水疗用品','07438473784)']

答案 1 :(得分:1)

使用括号将要匹配的模式分组到用于re.findall的正则表达式中:

s = '''David Smith (Best Pool and Spa Supplies / 07438473784)
Bessy McCarthur Jone (Dog Supplies / 0438-343522)'''
import re
print(re.findall(r'\(([^/]+?) */', s))

这将输出:

['Best Pool and Spa Supplies', 'Dog Supplies']

答案 2 :(得分:1)

这相当健壮,但是不会处理带有括号的名称。也就是说,它希望第一个(会超出名称的范围。但是,您可能会注意到该企业中有\).*\(,因此可以知道出了什么问题。

data = """
David Smith (Best Pool and Spa Supplies / 07438473784)
David Smith2 (Best Pool/Spa Supplies / 07438473784)
Bessy McCarthur Jone (Dog Supplies / 0438-343522)
Bessy McCarthur Jone2 (Dog (and cat) Supplies / 0438-343522)
Bessy (Bess, fails) McCarthur Jone3 (Dog Supplies / 0438-343522)
"""

lines = [line.strip() for line in data.splitlines() if line.strip()]

for line in lines:
    name,rest = line.split("(",1)
    name = name.strip()
    phone = rest.rsplit("/")[1].replace(")","").strip()
    biz = rest.rsplit("/",1)[0].strip()
    print("\n "+line)
    print(" =>name:%s: phone:%s:biz:%s:" % (name, phone,biz))

输出:

 David Smith (Best Pool and Spa Supplies / 07438473784)
 =>name:David Smith: phone:07438473784:biz:Best Pool and Spa Supplies:

 David Smith2 (Best Pool/Spa Supplies / 07438473784)
 =>name:David Smith2: phone:Spa Supplies:biz:Best Pool/Spa Supplies:

 Bessy McCarthur Jone (Dog Supplies / 0438-343522)
 =>name:Bessy McCarthur Jone: phone:0438-343522:biz:Dog Supplies:

 Bessy McCarthur Jone2 (Dog (and cat) Supplies / 0438-343522)
 =>name:Bessy McCarthur Jone2: phone:0438-343522:biz:Dog (and cat) Supplies:

 Bessy (Bess, fails) McCarthur Jone3 (Dog Supplies / 0438-343522)
 =>name:Bessy: phone:0438-343522:biz:Bess, fails) McCarthur Jone3 (Dog Supplies: