I'm struggling to e up with a regex that would find the ampersat in the beginning of words only. For example:
Here: The @dog went to the park.
But not here: The d@og went to the park.
Or here: The@dog went to the park.
Essentially, I just want to capture normal "mention" behavior, while omitting weird edge cases. I feel that this is mon enough that there must be some well-established regex for this.
Edit:
I tried with this:
/(@\w+)/gi
But, it captures cases that I do not wish to obtain.
I'm struggling to e up with a regex that would find the ampersat in the beginning of words only. For example:
Here: The @dog went to the park.
But not here: The d@og went to the park.
Or here: The@dog went to the park.
Essentially, I just want to capture normal "mention" behavior, while omitting weird edge cases. I feel that this is mon enough that there must be some well-established regex for this.
Edit:
I tried with this:
/(@\w+)/gi
But, it captures cases that I do not wish to obtain.
Share Improve this question edited Feb 2, 2016 at 20:47 Wiktor Stribiżew 627k41 gold badges496 silver badges611 bronze badges asked Feb 2, 2016 at 20:39 nmacnmac 6801 gold badge11 silver badges20 bronze badges 6- Please post your attempt. – Wiktor Stribiżew Commented Feb 2, 2016 at 20:40
-
That's an at-sign, ampersand is
&
. – Barmar Commented Feb 2, 2016 at 20:41 - What language is this? – z7r1k3 Commented Feb 2, 2016 at 20:43
- 1 Yes, its also called an 'ampersat', also, its javascript – nmac Commented Feb 2, 2016 at 20:43
- 1 @nmac I never knew it was called an ampersat. Thanks for the education! – Gary_W Commented Feb 2, 2016 at 20:52
2 Answers
Reset to default 16You may use the following regex:
/\B@\w+/g
\B
matches at a non-word boundary, thus, it requires a non-word (or start of string) to be right before @
.
See the regex demo
var re = /\B@\w+/g;
var str = 'The @dog went to the park.\nBut not here: The d@og went to the park.\nOr here: The@dog went to the park.';
var res = str.match(re);
document.body.innerHTML = "<pre>" + JSON.stringify(res, 0, 4) + "</pre>";
The regex should look something like this:
^@[A-Za-z]+|.+ @[A-Za-z]+
This will look for either @
at the beginning of the first word, or @
at the beginning of a word that follows.