正则表达式以匹配linux路径

时间:2020-04-08 16:09:31

标签: python regex

我尝试了许多在stackoverflow中找到的正则表达式,例如:This

import re

mystring = """
some string /bin/path and also /opt/something/bin/. 
Some other string /home/user/file.extension. 
Some more string \.out and \.cpp and \.extension. 
All these are paths and needs to be captured.
"""

我想用python re.sub用单词PATH替换所有路径。

output = """
some string PATH and also PATH. 
Some other string PATH. 
Some more string PATH and PATH. 
All these are paths and needs to be captured.
"""

1 个答案:

答案 0 :(得分:4)

您可以使用

mystring = re.sub(r'[/\\](?:(?!\.\s+)\S)+(\.)?', r'PATH\1', mystring)
print(mystring)

请参见a demo on regex101.com