在模式匹配RegEx Python中的文本

2024-10-03 04:40:16 发布

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

我需要以下模式的帮助,我现在挣扎了很多小时。 我有这样一段文字:

<<12/24/2015 00:00  userrrr>>
********** Text all char and symbols ************
<<12/24/2015 00:00 CET userr>>
Text all char and symbols
<<12/24/2015 00:00 GMT+1 userrrr>> Text in same line
<<12/24/2015 00:00 CET userrr>>
Text all characters and symbols
<<12/24/2015 00:00 GMT+1 userrrrrrr>> Text in same line
More Text all characters and symbols
<<12/24/2015 00:00 CET userrrrr>>
More text all characters and symbols
<<12/24/2015 00:00 CET userrrrrrrrrrr>>
More Text all characters and symbols

通过使用模式:

(\<<)(\d{2}/\d{2}/\d{4}\s\d{2}:\d{2})(.*?(?=>>))(>>)

日期时间和箭头之间的所有内容都是匹配的没错。很不幸, 我找不到一种方法来提取文本之间的模式。模式最后一组应该像(左箭头),(日期时间),(用户),(右箭头),(文本)这样。我越接近它,就使用:

(\<<)(\d{2}/\d{2}/\d{4}\s\d{2}:\d{2}\s\D{3}.*?(?=\s))\s(.*?(?=>>))(>>)((?s).*?(?=<<\d{2}/\d{2}))

但它与第一个和最后一个不匹配。Click Here to check the result(pythex.org)


Tags: andtextinmoreline模式箭头all
2条回答
(\<<)(\d{2}/\d{2}/\d{4}\s\d{2}:\d{2}\s\D{0,3}.*?(?=\s))\s(.*?(?=>>))(>>)((?s).*?(?=<<\d{2}/\d{2}|$))
                                                                                                ^^

最后一行需要给|$匹配。看到了吗演示。你知道吗

https://regex101.com/r/fM9lY3/51

我认为最简单的方法是逐行检查文件,并尝试用不同的正则表达式来匹配它们,一个用于标题行,另一个用于文本行。但如果你真的需要一枪就搞定,你可以:

(\<<)(\d{2}/\d{2}/\d{4}\s\d{2}:\d{2})(.*?(?=>>))(>>)\n\*+([^\*]+)\*+\n

相关问题 更多 >