如何用正则表达式匹配文本中带@前缀的多个用户名?
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\Bensures we only match @ symbols that aren't part of a word (like avoiding the @ in an email address such asuser@domain.com). If you don't care about that edge case, you can drop the\Band 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]+)*)
- Starts with a letter (
- 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
giflags:gfor global matching (find all usernames, not just the first),ifor 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
相关产品推荐
相关产品推荐

