【问题标题】:Python regular expression split by multiple delimiters由多个定界符分割的 Python 正则表达式
【发布时间】:2022-11-22 09:33:01
【问题描述】:

鉴于这句话“我想吃鱼,我想买车。因此,我必须赚钱。”

我想把句子分成

['我要吃鱼', '我要买车', 所以'我要赚钱']

我试图拆分句子

re.split('.|and', sentence)

但是,它将句子拆分为“.”、“a”、“n”和“d”。

我怎样才能用'。'分割句子和“和”?

【问题讨论】:

  • . 是正则表达式中的一个特殊字符,它匹配除换行符之外的任何字符。如果要匹配文字 .,请使用反斜杠 (\.) 将其转义或将其括在方括号 ([.]) 中。
  • 像这样的re.split('[.|](?:and)', sentence)
  • @cs95 请在发布前测试您的代码。

标签: python regex


【解决方案1】:

您需要在正则表达式中转义 .

import re

s = "I want to eat fish and I want to buy a car. Therefore, I have to make money."

re.split('.|and', s)

结果:

['I want to eat fish ',
 ' I want to buy a car',
 ' Therefore, I have to make money',
 '']

【讨论】:

    猜你喜欢
    • 2017-01-02
    • 2010-09-12
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-06
    • 1970-01-01
    相关资源
    最近更新 更多