从包含comm的字符串中提取子字符串

2024-09-30 01:29:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件中的字符串列表。我试图从每个字符串中提取一个子字符串并打印它们。字符串如下所示-

Box1 is lifted\nInform the manufacturer
Box2 is lifted\nInform the manufacturer
Box3, Box4 is lifted\nInform the manufacturer
Box5, Box6 is lifted\nInform the manufacturer
Box7 is lifted\nInform the manufacturer

我必须从每一行中提取\n之前的字符串并打印它们。我使用了下面的Python正则表达式来实现这一点-term = r'.*-\s([\w\s]+)\\n' 这个正则表达式适用于第1行、第2行和最后一行。但是它不适用于第3行和第4行,因为字符串中有一个,。我应该如何修改regex表达式以适应这种情况?你知道吗

预期结果-

Box1 is lifted
Box2 is lifted
Box3 Box4 is lifted
Box5 Box6 is lifted
Box7 is lifted

目前获得的结果-

Box1 is lifted
Box2 is lifted
Box2 is lifted
Box2 is lifted
Box7 is lifted

Tags: 文件the字符串列表ismanufacturerbox2box1
3条回答

逗号不是\W或\s字符集的一部分。term = r'.*-\s([\w\s,]+)\\n'应该是您想要的。你知道吗

对于这样的基本字符串操作,regex是一种过度杀伤力。使用内置的字符串方法,如partition和replace:

for line in lines:
    first, sep, last = line.partition('\n')
    newline = first.replace(',','')
    print (newline)

编辑。如果\n是从文件读取的行中的文字序列,请使用r'\n'而不是'\n'。你知道吗

如果格式一致,可以在换行符上拆分:

''.join(YOURSTRING.split('\n')[0].split(','))

编辑是因为我错过了删除逗号的部分。你知道吗

相关问题 更多 >

    热门问题