Fi中的Python正则表达式

2024-04-26 15:11:53 发布

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

我想从文件中按顺序提取行。例如,一个文件包含许多行,我想按顺序排列

journey (a,b) from station south chennai to station punjab chandigarh
journey (c,d) from station jammu katra to city punjab chandigarh
journey (e) from station 

假设上面是代码,我想从前两行提取以下信息:

这是第一个单词“旅程”的顺序--- 括号里会有两个词---- 然后有消息说--- 然后可能是单词站或城市--- 再加上任何一根绳子--- 然后再对我说一句话--- 然后它可以是单词station或city--

它的正则表达式是什么? 注:括号中的单词可能包含特殊字符,例如-,\


Tags: 文件tofromcity顺序单词括号station
1条回答
网友
1楼 · 发布于 2024-04-26 15:11:53

这将返回所需的元素:

import re

s = '''journey (a,b) from station south chennai to station punjab chandigarh
journey (c,d) from station jammu katra to city punjab chandigarh
journey (e) from station
journey (c,d) from station ANYSTRING jammu katra to ANYSTRING city punjab chandigarh
'''

matches_single = re.findall('journey (\([^,]+,[^,]+\)) from (\S+ \S+\s{0,1}\S*) to (\S+ \S+\s{0,1}\S*)', s)
for match in matches_single:
    print(match)
matches_line = re.findall('(journey \([^,]+,[^,]+\) from \S+ \S+\s{0,1}\S* to \S+ \S+\s{0,1}\S*)', s)
for match in matches_line:
    print(match)

相关问题 更多 >