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

如何用正则表达式匹配文本中带@前缀的多个用户名?

Solution to Match Multiple @-Prefixed Usernames

Got it, let's tweak your existing regex to catch those @-prefixed usernames scattered in a text string. Here's what you need:

Adjusted Regex

/\B@(?=.{3,20})([A-Za-z][A-Za-z0-9]+(?:[._][A-Za-z0-9]+)*)/gi

Breakdown of Changes

  • Removed ^ and $: Your original regex was built to match a single username as the entire string. Since we're hunting for usernames within a larger text, these anchors aren't needed anymore.
  • Added \B@: The \B ensures we only match @ symbols that aren't part of a word (like avoiding the @ in an email address such as user@domain.com). If you don't care about that edge case, you can drop the \B and just use @.
  • Kept your core username rules: The part after @ follows your original logic exactly:
    • Starts with a letter ([A-Za-z])
    • Followed by letters/numbers ([A-Za-z0-9]+)
    • Optional repeated segments of . or _ plus letters/numbers ((?:[._][A-Za-z0-9]+)*)
  • Retained length validation: The (?=.{3,20}) positive lookahead makes sure the username (after @) is between 3-20 characters long, just like your original rule.
  • Added gi flags: g for global matching (find all usernames, not just the first), i for case-insensitive matching.

Example Usage in JavaScript

const text = "Hello @tom.hardy have you met with @john.deo1";
const usernameRegex = /\B@(?=.{3,20})([A-Za-z][A-Za-z0-9]+(?:[._][A-Za-z0-9]+)*)/gi;

// Get all full matches (including @)
const fullMatches = text.match(usernameRegex);
console.log(fullMatches); // ["@tom.hardy", "@john.deo1"]

// Get just the usernames (without @) using matchAll
const matches = [...text.matchAll(usernameRegex)];
const usernames = matches.map(match => match[1]);
console.log(usernames); // ["tom.hardy", "john.deo1"]

This regex will correctly pick out all valid @-prefixed usernames in your text while sticking to your original username validation rules.

内容的提问来源于stack exchange,提问作者Saad Ahmed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:43:08