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

如何用正则表达式提取URL中/posts/前后的目标字符?

从URL中提取指定内容的正则表达式方案

针对你给出的URL格式(https://www.facebook.com/aaaaaa/posts/123456789/sdd),可以通过以下正则表达式精准提取两个目标内容:

正则模式

^https://www\.facebook\.com/([^/]+)/posts/(\d+)/

模式解释

  • ^https://www\.facebook\.com/:匹配URL开头的固定域名部分,. 用 \. 转义避免被当作通配符
  • ([^/]+):第一个捕获组,匹配除了/之外的任意字符,刚好对应/posts/之前的那段内容(示例中的aaaaaa)
  • /posts/:匹配固定的分隔符,确保定位到目标区域
  • (\d+):第二个捕获组,匹配一串连续数字,对应/posts/之后、下一个/之前的帖子ID(示例中的123456789)
  • /:匹配数字后的斜杠,确保只提取到帖子ID部分,不会包含后续内容

代码示例

Python 实现

import re

url = "https://www.facebook.com/aaaaaa/posts/123456789/sdd"
pattern = r"^https://www\.facebook\.com/([^/]+)/posts/(\d+)/"
match_result = re.match(pattern, url)

if match_result:
    target_before_posts = match_result.group(1)  # 输出:aaaaaa
    target_after_posts = match_result.group(2)   # 输出:123456789
    print(f"posts前内容: {target_before_posts}, posts后ID: {target_after_posts}")

JavaScript 实现

const url = "https://www.facebook.com/aaaaaa/posts/123456789/sdd";
const pattern = /^https:\/\/www\.facebook\.com\/([^\/]+)\/posts\/(\d+)\//;
const matchResult = url.match(pattern);

if (matchResult) {
  const targetBeforePosts = matchResult[1]; // 输出:aaaaaa
  const targetAfterPosts = matchResult[2];  // 输出:123456789
  console.log(`posts前内容: ${targetBeforePosts}, posts后ID: ${targetAfterPosts}`);
}

扩展说明

如果需要兼容Facebook的其他子域名(比如m.facebook.com),可以把正则开头的www\.替换成(?:www|m)\.,调整后的模式为:

^https://(?:www|m)\.facebook\.com/([^/]+)/posts/(\d+)/

(?:...) 是非捕获组,只会匹配内容但不会捕获成单独的分组,避免干扰目标内容的提取。

内容的提问来源于stack exchange,提问作者Quinoba

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:27:30