You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. Find what: .*\/([^\/]+)\/$
  2. Replace with: $1 (this gives you the captured segment)
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:01:06