ImGenie
ImGenie

Reputation: 323

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

Upvotes: 0

Views: 415

Answers (4)

castletheperson
castletheperson

Reputation: 33486

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.

Upvotes: 3

Pankaj Dubey
Pankaj Dubey

Reputation: 146

public static void main(String[] args)
{
    char[] word = "@SomeWord".toCharArray();
    if (word[0] == '@')
    {
        System.out.println("Starts with @");
    }
    else
    {
        System.out.println("Not Starts with @");
    }

}

Upvotes: 0

Piyg
Piyg

Reputation: 244

I think this is what you are looking for.

(?<!\w)@\w+

This matches @Steve but doesn't match Hello@Steve. 

Upvotes: 1

gaganso
gaganso

Reputation: 3011

Try this regex:

@\b\w+\b

You can test regexes here

Upvotes: 0

Related Questions