Regex - Find string that has 5 or more mentions in it

Viewed 40

Trying to detect whether a message has 5 or more mentions in it.

For example:

@Boddy is doing great with @shirly @rebecca @jimmy and @mom

Above will count as one match. This will not count as a match:

@Boddy is doing great with @shirly @rebecca @jimmy and ...

Preferably, @@@@@ should not count either, but not too important!

I've tried

@([^@ ]+){5,}

But no luck, it highlights all 5 instead of the whole string.

3 Answers

Use a pattern which covers the entire string:

^.*@.*@.*@.*@.*@.*$

Demo

You can change your pattern by adding the @ after the negated character class, and also end the pattern with the negated character class.

Using the negated character class also prevents unnecessary backtracking. If you don't need the capture group, you can use a non capture group (?:

Note that [^@]* can also match a newline

^([^@]*@){5,}[^@]*$

See a regex demo.


If you want to match mentions, @@@@@ should not match and you don't want to match crossing newlines, you can prepend \B before the @ to assert a non word boundary.

Then match at least a single char other than a whitespace char or @ after matching the @.

^[^@\n\r]*(\B@[^@\s][^@\n\r]*){5,}$

See another regex demo.

Assumptions:

  • Looking at your data you'd maybe want to assert that the '@' is preceded with either the start-line anchor or a space;
  • You'd like to avoid concatenated '@'s to prevent false positives.

With these in mind, maybe you could try:

^(?:[^@]*(?<!\S)@\w+){5}.*$

Seen an online demo.


  • ^ - Start-line anchor;
  • (?:- Open non-capture group;
    • [^@]* - 0+ (Greedy) characters other than '@';
    • (?<!\S) - Negative lookbehind to assert position is not preceded by a non-whitespace;
    • @\w+ - A literal '@' with 1+ (Greedy) word-characters;
    • ){4} - Close non-capture group and match 4 more times;
  • .* - Any 0+ (Greedy) characters;
  • $ - An end-line anchor.
Related