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

如何使用正则表达式从多种URL字符串中提取appName关键词

Extract appName from All URL Examples

Got it, let's fix your regex so it works for all four URL cases you listed. Your current pattern /(?<=webapp/)(.*)(?=#)/g relies on a # being present to terminate the match, which is why it fails for examples 1 and 4. Here's a better approach:

The Updated Regex

/(?<=myapp\/)([^\/#]+)/

How It Works

  • (?<=myapp\/): Positive lookbehind to target the position right after myapp/ (we escape the slash with \/ to avoid regex syntax conflicts)
  • ([^\/#]+): Captures one or more characters that are not a slash (/) or hash (#). This ensures we stop matching as soon as we hit either of these characters, or the end of the string—covering all your edge cases.

Testing Against All Examples

Let’s confirm it works for every URL:

  • Example 1: http://localhost:1001/myapp/appName → Matches appName (stops at end of string)
  • Example 2: http://localhost:1001/myapp/appName#!/ → Matches appName (stops at #)
  • Example 3: http://localhost:1001/myapp/appName#!/Test → Matches appName (stops at #)
  • Example 4: http://localhost:1001/myapp/appName/test/what → Matches appName (stops at /)

Usage Example (JavaScript)

If you’re implementing this in JS, here’s a quick way to extract the value across all your URLs:

const urls = [
  "http://localhost:1001/myapp/appName",
  "http://localhost:1001/myapp/appName#!/",
  "http://localhost:1001/myapp/appName#!/Test",
  "http://localhost:1001/myapp/appName/test/what"
];

const regex = /(?<=myapp\/)([^\/#]+)/;
urls.forEach(url => {
  const appName = url.match(regex)[0];
  console.log(`Extracted appName: ${appName}`);
});

This will log appName for every entry in the list.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:41:49