-1

When trying to parse a string a string for mentions I was using this regex: .*@${username}.* where ${username} is a parameter.

if ${username} = 'c'

then this becomes .*@c.* so this will incorrectly match something like hello @cat.

I need a regex that matches the entire string:

@c
hello @c
@c hello
hello @c hello

and does not match:

@cat
  • It doesn't have to be one regex. It could be multiple ones that cover all cases without interfering with another case.
atkayla
  • 8,143
  • 17
  • 72
  • 132
  • This seems to work: `(^|\s)@c(\s|$)`. Probably a bunch of better ways to do it, not a regex guru. – Tibrogargan Apr 23 '17 at 07:05
  • 1
    Possible duplicate of [Regex match entire words only](http://stackoverflow.com/questions/1751301/regex-match-entire-words-only) – JJJ Apr 23 '17 at 07:05
  • @JJJ problem with \b is the `@` character, so it's not the same question – Tibrogargan Apr 23 '17 at 07:06
  • 1
    @Tibrogargan Why would that make any difference? – JJJ Apr 23 '17 at 07:07
  • @JJJ The answer you linked uses \b (and/or \w) to delimit the term (a word) being searched for, but the problem is that @ is not a word character so there is not boundary before or after it. The term is not a word. – Tibrogargan Apr 23 '17 at 07:10
  • @Tibrogargan The OP is interested only in the ending of the word. Surely they have the common sense to adapt the duplicate to their code (`@c\b`). – JJJ Apr 23 '17 at 07:14
  • @Tibrogargan I appreciate the effort! JJJ: Thanks! I just learned the term "word boundary" from this. Sorry for duplicate question. – atkayla Apr 23 '17 at 07:33

2 Answers2

0

Just make sure that the user name is not followed by a username constituant: @$username\([^a-z]\|$\). Note that depending on the regexp parser you might need to remove the backslashes.

kmkaplan
  • 18,655
  • 4
  • 51
  • 65
0

This seems to work.

.*@\bc\b.*

https://regex101.com/r/OYjmvQ/1

I was also wondering why it wasn't working in my actual code though (Java) and derp: Java Regex Word Boundaries

had to be double escaped:

.*@\\bc\\b.*
Community
  • 1
  • 1
atkayla
  • 8,143
  • 17
  • 72
  • 132