我是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)在任何其他特殊字符或空格结束之前的最后/
这应该用引号中的相对路径替换。 有人可以帮我找到正确的正则表达式。
答案 0 :(得分:1)
因为它是所有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)
输出:
String that has a path as "$relativePath/moreofPath/evenmore/" with additional text
我正在做的是抓住比赛中的比赛并替换替换比赛。请注意。*使其贪得心up直到最后/
答案 1 :(得分:0)
使用匹配任何路径的正则表达式跟随用户名,只要它不是空格
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'