Skip to main content
 首页 » 编程设计

python之如何从字符串末尾向后剥离模式或单词

2025年05月04日22arxive

我有这样一个字符串:

<foo><bar><k2><v1>aaa<b>bbb</b>ccc</v1></k2></bar><foo> 

我想从字符串中去除前 3 个开始标签 和 最后 3 个结束标签。我事先不知道标签名称。

我可以用 re.sub(r'<[^<>]+>', '', in_str, 3)) 去除前 3 个字符串.如何去除结束标签?应该留下的是:

<v1>aaa<b>bbb</b>ccc</v1> 

我知道我也许可以“做对”,但实际上我不希望出于我的目的进行 xml 或 html 解析,这是为了帮助我可视化某些类的 xml 表示。

相反,我意识到这个问题很有趣。看来我cannot只需使用正则表达式向后搜索,即。 从右到左。因为那似乎是unsupported :

If you mean, find the right-most match of several (similar to the rfind method of a string) then no, it is not directly supported. You could use re.findall() and chose the last match but if the matches can overlap this may not give the correct result.

但是.rstrip不善言词,也不会造句。

我看了Strip HTML from strings in Python但我只想剥离最多 3 个标签。

这里可以使用什么方法?我是否应该反转字符串(本身很丑并且由于'<>')。做标记化(那为什么不解析呢?)?或者根据从左到右的匹配创建静态结束标记?

从字符串末尾去除模式应遵循哪种策略?

请您参考如下方法:

最简单的方法是使用老式字符串拆分和限制拆分:

in_str.split('>', 3)[-1].rsplit('<', 3)[0] 

演示:

>>> in_str = '<foo><bar><k2><v1>aaa<b>bbb</b>ccc</v1></k2></bar><foo>' 
>>> in_str.split('>', 3)[-1].rsplit('<', 3)[0] 
'<v1>aaa<b>bbb</b>ccc</v1>' 

str.split()和 str.rsplit() with a limit 会将字符串从开始或结束拆分到限制次数,让您选择剩余的未拆分。