【问题标题】:List index out of range, splitting regular expression match列表索引超出范围,拆分正则表达式匹配
【发布时间】:2017-10-30 16:04:50
【问题描述】:

由于某种原因,我的代码中的这一小部分给了我一个问题。我一直在试图弄清楚为什么它给了我一个“列表索引超出范围”错误

#This works fine, and finds a match
if re.search("Manufacturer\/Distributor name:?", arg) != None:

    #---->This is giving me the problem, "List index out of range"<----
    address = arg.split("Manufacturer\/Distributor name:?", 1)[1]

这是我要喂它的 arg:

产品名称:Tio Nacho 洗发水墨西哥草药 推荐用途:洗发水 制造商/分销商名称: Garcoa Laboratories, Inc. 26135 Mureau Road Calabasas, CA 91302 (818) 225 - 0375 紧急电话号码: CHEMTREC 1 - 800 - 424 - 9300 2 .

当我将它设置为 [1] 时,结果如下:

List index out of range

当我将拆分设置为 [0] 时,结果如下:

/Distributor name: Garcoa Laboratories, Inc. 26135 Mureau Road Calabasas, CA 91302 (818) 225 - 0375 Emerg ency telephone number: CHEMTREC 1 - 800 - 424 - 9300 2 .

我正在尝试得到这个结果:

Garcoa Laboratories, Inc. 26135 Mureau Road Calabasas, CA 91302 (818) 225 - 0375 Emerg ency telephone number: CHEMTREC 1 - 800 - 424 - 9300 2 .

它与它匹配,但由于某种原因拆分不希望工作。我错过了什么?为什么它会给出 [0] 的结果

感谢您的帮助!

【问题讨论】:

  • split() 的参数不是正则表达式,它只是一个普通字符串。所以它没有分裂,因为输入字符串中没有?
  • 另外,您需要转义反斜杠\ 。哦,要使用正则表达式,请使用 re.search() 而不是 split() 函数

标签: python regex python-2.7


【解决方案1】:

str.split()不带正则表达式,需要使用re.split()

address = re.split(r'Manufacturer\/Distributor name:?', arg, 1)[1]

您还应该养成使用原始字符串作为正则表达式的习惯,否则您需要转义\

【讨论】:

    【解决方案2】:

    我假设arg 是一个字符串。 string.split() 不接受正则表达式作为分隔符。你可以阅读它here

    您应该使用arg.split("Manufacturer/Distributor name", 1)[1]

    【讨论】:

    • 但显然: 是可选的,所以它可能不存在。
    • @Barmar 按照正则表达式,是的,你是对的。代码已修复。
    • 现在它将在结果中包含:
    • @Barmar 是的,你的回答更准确:)
    猜你喜欢
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    • 2013-05-31
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多