如何在SQL中提取URL中斜杠后的第一个单词
提取URL域名后斜杠后的第一个单词的实现方法
以下是几种常用工具的落地实现方案,直接套用即可满足需求:
Python 实现
可以借助URL解析模块或直接字符串分割来完成:
方法1:用urllib.parse解析URL
from urllib.parse import urlparse def get_first_path_word(url): parsed = urlparse(url) path_parts = parsed.path.strip('/').split('/') return path_parts[0] if path_parts else '' # 测试示例 print(get_first_path_word("https://stackoverflow.com/questions/ask")) # 输出 questions print(get_first_path_word("https://qwerty.com/search/go")) # 输出 search
方法2:直接字符串分割
def get_first_path_word(url): # 跳过协议部分,定位到域名后的第一个斜杠 after_protocol = url.split('://')[-1] first_slash_pos = after_protocol.find('/') if first_slash_pos == -1: return '' # 截取到下一个斜杠前的内容 next_slash_pos = after_protocol.find('/', first_slash_pos + 1) if next_slash_pos == -1: return after_protocol[first_slash_pos+1:] return after_protocol[first_slash_pos+1:next_slash_pos] # 测试示例 print(get_first_path_word("https://stackoverflow.com/questions/ask")) # 输出 questions print(get_first_path_word("https://qwerty.com/search/go")) # 输出 search
Excel 公式实现
假设URL存放在A1单元格,直接在目标单元格输入以下公式:
=MID(A1,FIND("/",A1,FIND("//",A1)+2)+1,FIND("/",A1,FIND("/",A1,FIND("//",A1)+2)+1)-FIND("/",A1,FIND("//",A1)+2)-1)
公式逻辑:先定位到域名后的第一个斜杠,再找到下一个斜杠的位置,最终提取两者之间的内容。
SQL 实现
MySQL 版本
假设表名为url_table,URL字段为url_content:
SELECT SUBSTRING_INDEX( SUBSTRING(url_content, LOCATE('/', url_content, LOCATE('//', url_content) + 2) + 1), '/', 1 ) AS first_path_segment FROM url_table;
SQL Server 版本
SELECT SUBSTRING( url_content, CHARINDEX('/', url_content, CHARINDEX('//', url_content) + 2) + 1, CHARINDEX('/', url_content, CHARINDEX('/', url_content, CHARINDEX('//', url_content) + 2) + 1) - CHARINDEX('/', url_content, CHARINDEX('//', url_content) + 2) - 1 ) AS first_path_segment FROM url_table;
内容的提问来源于stack exchange,提问作者user20391531
相关产品推荐
相关产品推荐

