Regex技术求助:提取URL末尾元素并将连字符替换为空格
Regex Solution to Extract and Transform Target URL Segment
Got it, let's tackle this problem step by step. Here's a regex approach that works reliably no matter what unpredictable content comes before your target segment:
Step 1: Regex to Capture the Target Segment
Use this regex pattern to isolate the text between the second-to-last and final slashes:
\/([^\/]+)\/$
Breakdown of the Pattern:
\/: Escaped forward slash (we escape it because/acts as a delimiter in many regex engines)([^\/]+): Capturing group that matches one or more characters not equal to a forward slash — this is exactly the segment you want to extract\/$: Matches the final forward slash, anchored to the end of the string with$to ensure we're only targeting the last segment before the trailing slash
Step 2: Replace Hyphens with Spaces
Once you've captured the segment from the regex match, simply replace all hyphens (-) with spaces.
Example Implementations
Python
import re url = "https://example.com/notwantedstring/anotherunwantedstring/i-want-this-string/" match_result = re.search(r"/([^/]+)/$", url) if match_result: target_text = match_result.group(1) final_output = target_text.replace("-", " ") print(final_output) # Output: i want this string
JavaScript
const url = "https://example.com/notwantedstring/anotherunwantedstring/i-want-this-string/"; const regexPattern = /\/([^\/]+)\/$/; const match = url.match(regexPattern); if (match) { const transformedText = match[1].replace(/-/g, " "); console.log(transformedText); // Output: i want this string }
Regex Replace Tool (e.g., Sublime Text, VS Code)
If you're using a text editor's find-and-replace with regex:
- Find what:
.*\/([^\/]+)\/$ - Replace with:
$1(this gives you the captured segment) - Then do a second replace: find
-, replace with(space)
Why This Works
The $ anchor ensures we're always looking at the end of the URL, so no matter how long or variable the prefix is, we bypass all irrelevant segments and zero in on the one between the last two slashes.
内容的提问来源于stack exchange,提问作者Jack Samson
相关产品推荐
相关产品推荐

