I'm new to regex and was trying to solve the below problem.
Input String - String that has a path as /Users/MyName/moreofPath/ with additional text
Output String - String that has a path as "$relativePath/moreofPath/" with additional text
The absolute path in the sentence is to be recognized by
1) where /Users/MyName
starts
2) where last /
that comes before any other special character or space ends
This should be replaced by relative path in quotes. Can someone please help me find correct regex for this.
Since it's all Python, I would do something like this:
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)
Output:
String that has a path as "$relativePath/moreofPath/evenmore/" with additional text
What I'm doing is grabbing the matches in the from the parans and substituting them back in the replacement. Note that the .* makes it greedy up to the last /
using regex that match any path follow by username as long its not space
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'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.