DD
DevDash

Regex for Twitter Handle

Regex Pattern

^@?(\w){1,15}$

Twitter/X handle, 1-15 chars, optional @

Quick Answer

The regex pattern for twitter handle is `^@?(\w){1,15}$`. Twitter/X handle, 1-15 chars, optional @. This works in JavaScript, Python, Ruby, PHP, Java, and most regex engines that support PCRE syntax.

Test Examples

InputResult
@jack✓ Matches
elonmusk✓ Matches
@AI_news_123✓ Matches
@handle-with-dash✗ No match
toolonghandle123456✗ No match
@✗ No match

Code Examples

javascript

const regex = /^@?(\w){1,15}$/;
const isValid = regex.test(value);

python

import re
pattern = r'^@?(\w){1,15}$'
if re.match(pattern, value):
    print("valid")

ruby

pattern = /^@?(\w){1,15}$/
if value =~ pattern
  puts "valid"
end

php

if (preg_match('/^@?(\w){1,15}$/', $value)) {
    echo "valid";
}

java

String pattern = "^@?(\\w){1,15}$";
boolean isValid = value.matches(pattern);

Frequently Asked Questions

Related Regex Patterns

Want API access + no ads? Pro coming soon.