2

我有一个输入字段,我的用户正在以各种格式输入他们的 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 中提取。不知道如何搜索 @ 之后的内容

4

2 回答 2

6

您需要一个匹配@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]) 
  }
})

于 2020-05-19T04:31:54.027 回答
0

建立在@Phil 的回答之上。它会忽略带有句点“。”的 Instagram 用户名。在他们中。

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

这也应该处理带有句点的 insta 用户名。

于 2021-05-27T07:55:56.777 回答