如何使用正则表达式从多种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 aftermyapp/(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→ MatchesappName(stops at end of string) - Example 2:
http://localhost:1001/myapp/appName#!/→ MatchesappName(stops at#) - Example 3:
http://localhost:1001/myapp/appName#!/Test→ MatchesappName(stops at#) - Example 4:
http://localhost:1001/myapp/appName/test/what→ MatchesappName(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
相关产品推荐
相关产品推荐

