简体   繁体   English

用于检查Java中以字符'@'开头的单词的出现的正则表达式

[英]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 . 我正在尝试搜索以'@'开头的单词的出现,@ 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_]. 到目前为止,我尝试过的是“。 \\ b @ steve \\ b。 ”,但是\\ b仅匹配以[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 谢谢

You're correct, a \\b can't find a word-boundary there because @ isn't a word character. 没错, \\b不能在其中找到单词边界,因为@不是单词字符。 You could use a look-behind: 您可以使用后退式:

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

Regex101 Example Regex101示例

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. 请注意,在上述正则表达式中, \\b的末尾是不必要的,因为反之,量词将一直移到单词的末尾。

I think this is what you are looking for. 我认为这就是您想要的。

(?<!\w)@\w+

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

Try this regex: 试试这个正则表达式:

@\\b\\w+\\b

You can test regexes here 您可以在这里测试正则表达式

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 @");
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM