Python 裁剪出字符串的一部分并使用正则表达式打印

Python 裁剪出字符串的一部分并使用正则表达式打印,python,regex,string,Python,Regex,String,我正在尝试裁剪字符串列表的一部分并打印它们。数据如下所示- 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

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

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
到目前为止我都试过了-

首先,我将
逗号
替换为
空格
-
a=name.replace(',','')

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

我现在收到的输出是-

Books are on the table
Pens are in the bag
Pencils erasers ruler cannot be found
Laptops headphones are lost
我应该在表达式中添加什么来打印第3行和第4行


TIA

我知道很多人喜欢用正则表达式把自己的想法扭曲成一团,但为什么不呢

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
您可以匹配并删除以反斜杠和
n
组合开头的行部分,或使用以下字符匹配并删除所有标点符号(非单词和非空白):

详细信息

  • \\n.*
    -a
    \
    n
    ,然后是行的其余部分
  • |
    -或
  • [^\w\s]+
    -1个或多个字符,而不是单词和空白字符

如果您需要确保
\n
之后有大写字母,您可以在模式中
n
之后添加
[A-Z]

尝试我得到以下错误-
AttributeError:“str”对象没有属性“groups”
(在帖子中更新了我的代码)不能有任何组,它是
re.sub
,它会删除匹配项。我还有一个小的附加查询,我正在努力处理。如果数据看起来像
V0.00-书本在表上\n将它们向上勾选
V0.00
中的每个数字的范围为0-3。我需要做哪些修改才能获得输出
表中的书籍
?我试图搜索
-
,并删除之前的字符串。但它不起作用,我不确定我是否满足这个要求。如果您的意思是应该删除从行首到第一个空格的所有文本,请使用
a = re.sub(r'\\n.*|[^\w\s]+', '', a)