Regex to match word beginning with @

前端 未结 4 1105
长情又很酷
长情又很酷 2021-01-13 22:21

I am trying to develop some regex to find all words that start with an @:

I thought that \\@\\w+ would do it but this also matches words that have @ con

相关标签:
4条回答
  • 2021-01-13 22:43

    And what about a non-Regex approach?

    C# version:

    string input = "word1 word2 @word3 ";
    string[] resultWords = input.Split(' ').ToList().Where(x => x.Trim().StartsWith("@")).ToArray();
    

    VB.NET version:

    Dim input As String = "word1 word2 @word3 "
    Dim resultWords() As String = input.Split(" "c).ToList().Where(Function(x) x.Trim().StartsWith("@")).ToArray
    
    0 讨论(0)
  • 2021-01-13 22:47

    How about a negative look-behind:

    (?<!\w)@\w+
    
    0 讨论(0)
  • 2021-01-13 22:54

    Try using

    (?<=^|\s)@\w+
    

    Can't remember if c# allows alternation in a look behind

    RegExr

    0 讨论(0)
  • 2021-01-13 22:55

    Use \B@\w+ (non-word boundary).

    For example:

    string pattern = @"\B@\w+";
    foreach (var match in Regex.Matches(@"@help me@ ple@se @now", pattern))
        Console.WriteLine(match);
    

    output:

    @help
    @now
    

    BTW, you don't need to escape @.

    http://ideone.com/nsT015

    0 讨论(0)
提交回复
热议问题