Reputation: 421
In regular expression, how do I look for matches that start with an @symbol? The symbol cannot be in the middle of a word (link in an email address).
For example, a string that looks like this:
@someone's email is [email protected] and @someoneelse wants to send an email.
The expression I'd use is /^@[\w]/g
It should return:
@someone's
@someoneelse
The expression I use doesn't seem to work.
Upvotes: 4
Views: 8580
Reputation: 640
You can use lodash, if you are using JavaScript.
words function from javascript takes two params. first param is for sentence and the second one is optional. You can pass regex which will find the word with starting letter "@".
import _ from "lodash";
_.words(sentence, /\B@\S+/g);
Upvotes: 1
Reputation: 70732
You can utilize \B
which is a non-word boundary and is the negated version of \b
.
var s = "@someone's email is [email protected] and @someoneelse wants to send an email.",
r = s.match(/\B@\S+/g);
console.log(r); //=> [ '@someone\'s', '@someoneelse' ]
Upvotes: 6
Reputation: 19573
/(^|\s)@\w+/g
The [\w]
only matches a single word character, so thats why your regex only returns @s
. \w+
will match 1 or more word characters.
If you want to get words at the beginning of the line or inside the string, you can use the capture group (^|\s)
which does either the beginning of the string or a word after a whitespace character.
DEMO
var str="@someone's email is [email protected] and @someoneelse wants to send an email.";
console.log(str.match(/(^|\s)@\w+/g)); //["@someone", " @someoneelse"]
Upvotes: 0