【问题标题】:Cropping out a portion of a string and printing using regex裁剪出字符串的一部分并使用正则表达式打印
【发布时间】:2017-11-29 21:21:05
【问题描述】:

我正在尝试裁剪字符串列表的一部分并打印它们。数据如下所示 -

Books are on the table\nPick them up
Pens are in the bag\nBring them
Cats are roaming around
Dogs are sitting
Pencils, erasers, ruler cannot be found\nSearch them
Laptops, headphones are lost\nSearch for them

(这只是文件中 100 行数据中的几行)

我必须在第 1,2,5,6 行的 \n 之前裁剪字符串并打印出来。我还必须与它们一起打印第 3,4 行。预期输出 -

Books are on the table
Pens are in the bag
Cats are roaming around
Dogs are sitting
Pencils erasers ruler cannot be found
Laptops headphones are lost

到目前为止我所尝试的 -

首先我将comma 替换为space - a = name.replace(',',' ');

然后我使用正则表达式来裁剪子字符串。我的正则表达式是-b = r'.*-\s([\w\s]+)\\n'。我无法打印不存在 \n 的第 3 行和第 4 行。

我现在收到的输出是 -

Books are on the table
Pens are in the bag
Pencils erasers ruler cannot be found
Laptops headphones are lost

我应该在表达式中添加什么来打印出第 3 行和第 4 行?

TIA

【问题讨论】:

  • 我收到以下错误 - AttributeError: 'str' object has no attribute 'groups'(在帖子中更新了我的代码)
  • 不能有任何组,它是re.sub,它会删除匹配项。

标签: python regex string


【解决方案1】:

您可以匹配并删除以反斜杠和n 的组合开头的行部分,或使用re.sub 的所有标点符号(非单词和非空格)字符:

a = re.sub(r'\\n.*|[^\w\s]+', '', a)

regex demo

详情

  • \\n.* - \n,然后是该行的其余部分
  • | - 或
  • [^\w\s]+ - 1 个或多个除单词和空格字符以外的字符

如果你需要确保\n后面有一个大写字母,你可以在模式中n后面加上[A-Z]

【讨论】:

  • 我有一个额外的小问题正在努力解决。如果数据看起来像 V0.00 - Books are on the table\nPick them up 并且 V0.00 中的每个数字范围为 0-3。我需要进行哪些修改才能获得输出Books are on the table?我试图搜索 - 并在此之前删除字符串。但它不起作用
  • 不确定我是否满足此要求。如果您的意思是应该删除从行首到第一个空格连字符空格的所有文本,请使用(?m)^.*? - |\\n.*|[^\w\s]+
【解决方案2】:

我知道很多人喜欢用正则表达式将他们的思想扭曲成结,但为什么不呢,

with open('geek_lines.txt') as lines:
    for line in lines:
        print (line.rstrip().split(r'\n')[0])

写起来简单,读起来简单,似乎产生了正确的结果。

Books are on the table
Pens are in the bag
Cats are roaming around
Dogs are sitting
Pencils, erasers, ruler cannot be found
Laptops, headphones are lost

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 2018-10-16
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多