-1

I need to know how mention works, how should find mentions during a text. are we must to find first of '@' and last of not @"^[a-zA-Z0-9_,]+$"

thank you for sharing your experience

string comment=" hi @fri.tara3^";
mention is : "@fri.tara3"
ara
  • 131
  • 1
  • 1
  • 8

1 Answers1

2

Looks like a good fit for regular expressions. There are multiple ways to solve this.

Here's the simplest one:

 (?<mention>@[a-zA-Z0-9_.]+)[^a-zA-Z0-9_.]
  • it searches matching characters followed by non-matching character. [^ ... ] does the negation bit
  • (?<mention> ... ) declares an explictit group to capture mention without including the non-matching character immediately following the mention.
  • not that this pattern requires a non-matching character after mention, so if it matters work around that.

A cleaner pattern would use a feature called look-ahead:

@[a-zA-Z0-9_.]+?(?![a-zA-Z0-9_.])
  • (?!) is negative lookahead. Meaning "only match if it is NOT followed by this"
  • named capture not required as lookahead does not consume the lookahead part.
  • It supports multiple mention lookups by adding using non-greedy quantifier +?. This ensures that matched mention is as short as possible.

Lookaheads are a tad less known and may become a pain to read if pattern grows too long. But it is a useful tool to know.

Full example using C#:

string comment = "hi @fri.tara3^ @hjh not a mention @someone";
const String pattern = "@[a-zA-Z0-9_.]+?(?![a-zA-Z0-9_.])";
var matches = Regex.Matches(comment, pattern);

for (int i = 0; i < matches.Count; i++)
{
    Console.WriteLine(matches[i].Value);
}
Imre Pühvel
  • 4,468
  • 1
  • 34
  • 49
  • thank you , how about finding multi @ like `"hi @fri.tara3^ @hjh"` am I must to use something like this: `comment=comment.Substring(indexofLastFind,...)` – ara May 14 '16 at 08:24
  • Regex can find all matches for you in one pass. See updated example in answer. – Imre Pühvel May 14 '16 at 08:31
  • you are magical, unbelievable ! thank you, thank you very much :* – ara May 14 '16 at 08:37