我有一个文件中的字符串列表。我试图从每个字符串中提取一个子字符串并打印它们。字符串如下所示-
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
逗号不是\W或\s字符集的一部分。
term = r'.*-\s([\w\s,]+)\\n'
应该是您想要的。你知道吗对于这样的基本字符串操作,regex是一种过度杀伤力。使用内置的字符串方法,如partition和replace:
编辑。如果\n是从文件读取的行中的文字序列,请使用r'\n'而不是'\n'。你知道吗
如果格式一致,可以在换行符上拆分:
编辑是因为我错过了删除逗号的部分。你知道吗
相关问题 更多 >
编程相关推荐