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