user3415862 user3415862 - 6 months ago 11
Android Question

Regular expression to check occurrence of a word that starts with character '@' in java

I am trying to search for occurrence of a word starts with '@', Say @steve. But I have no success.

What I have tried so far is this ".\b@steve\b." but \b matches only words which starts with [a-zA-Z0-9_].

If the question is too broad or anybody needs a code sample please let me know I'll post

Any help is appreciated.

Thanks

Answer

You're correct, a \b can't find a word-boundary there because @ isn't a word character. You could use a look-behind:

(?<!\\w)@steve\\b

Regex101 Example

A general case regex would simply be:

(?<!\\w)@\\w+

Note that in the above regex, the ending \b is unnecessary because the quantifier will go to the end of the word anyway.