首页 > 解决方案 > 如何从字符串中提取Instagram用户名

问题描述

我有一个输入字段,我的用户正在以各种格式输入他们的 instagram 用户名

@username
https://www.instagram.com/username
https://www.instagram.com/username/
instagram.com/username

如何仅提取用户名

(?:(?:http|https):\/\/)?(?:www.)?(?:instagram.com|instagr.am)\/([A-Za-z0-9-_]+)

我可以从 URL 中提取。不知道如何搜索 @ 之后的内容

标签: javascript

解决方案


您需要一个匹配@URL 版本的任一或各种形式的正则表达式作为用户名的前缀,后跟可选的正斜杠。

像这样的东西

/^(?:@|(?:https?:\/\/)?(?:www\.)?instagr(?:\.am|am\.com)\/)?(\w+)\/?$/

打破它

^
(?:
  @                     - literal "@"
  |                     - or
  (?:https?:\/\/)?      - optional HTTP / HTTPS scheme
  (?:www\.)?            - optional "www."
  instagr(?:\.am|\.com) - "instagram.com" or "instgr.am"
  \/                    - forward-slash
)?                      - the whole prefix is optional
(\w+)                   - capture group for the username. Letters, numbers and underscores
\/?                     - optional trailing slash
$

const inputs = [
  '@username', 
  'https://www.instagram.com/username', 
  'https://www.instagram.com/username/', 
  'instagram.com/username', 
  'handsome_jack',
  'http://example.com/handsome'
]

const rx = /^(?:@|(?:https?:\/\/)?(?:www\.)?instagr(?:\.am|am\.com)\/)?(\w+)\/?$/

inputs.forEach(input => {
  let match = rx.exec(input) 
  if (match) {
    console.log(input, match[1]) 
  }
})


推荐阅读