Python Regex将文本中的绝对路径替换为引号中添加的相对路径

2024-09-28 20:47:51 发布

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

我是regex新手,正在尝试解决以下问题。在

输入字符串-String that has a path as /Users/MyName/moreofPath/ with additional text

输出字符串-String that has a path as "$relativePath/moreofPath/" with additional text

句子中的绝对路径是由

1)从/Users/MyName开始

2)在任何其他特殊字符或空格之前的最后一个/结尾

应该用引号中的相对路径替换它。 有人能帮我找到正确的正则表达式吗。在


Tags: path字符串textstringthataswithusers
2条回答

既然都是Python,我会做如下的事情:

import re

thestring = "String that has a path as /Users/MyName/moreofPath/evenmore/ with additional text"
regex = "(.*?)/Users/MyName/(.*/)"
thestring = re.sub(regex, r'\1"$relativePath/\2"' , thestring)
print (thestring)

输出:

^{pr2}$

我要做的是从帕兰人那里抢来火柴,然后把它们换回来。请注意,*使它贪婪到最后/

使用正则表达式匹配任何路径跟在用户名后面,只要它不是空格

import re
input_string = "String that has a path as /Users/MyName/moreofPath/ with additional text"
output_string = re.sub(r'/Users/MyName([^\s]*)', r'"$relativePath\1"', input_string)
# 'String that has a path as "$relativePath/moreofPath/" with additional text'

相关问题 更多 >