I would like to use (^|\s)@\w+($|\s) because you can get emails in your input like :
a @twitter username and a [email protected] another @twitterUserName
So you can use :
String text = "a @twitter username and a [email protected] another @twitterUserName";
text = text.replaceAll("(^|\\s)@\\w+($|\\s)", "$1$2");
// Output : a username and a [email protected] another
Details :
(^|\s) which match ^ start of string or | a space \s
@\w+ match @ followed by one or more word characters which is equivalent to [A-Za-z0-9_]
($|\s) which match $ end of string or | a space \s
If you want to go deeper to specify the correct syntax of twitter usernames i read this article here they mention some helpful information :
Your username cannot be longer than 15 characters. Your name can be longer (50 characters), but usernames are kept shorter for the
sake of ease.
A username can only contain alphanumeric characters (letters A-Z, numbers 0-9) with the exception of underscores, as noted above. ...
From this rules you use this regex as well :
(?i)(^|\s)@[a-z0-9_]{1,15}($|\s)
text = text.replaceAll("@\\w+", "");.\wmeans word characters,+means a greedy quantifier matching 1 or more. Documentation.