-1

I'm a RegEx novice, so I'm hoping someone out there can give me a hint.

I want to find a straightforward way (using RegEx?) to extract a list/array of values that match a pattern from a string.

If source string is "Hello @bob and @mark and @dave", I want to retrieve a list containing "@bob", "@mark" and "@dave" or, even better, "bob", "mark" and "dave" (without the @ symbol).

So far, I have something like this (in C#):

string note = "Hello, @bob and @mark and @dave";
var r = new Regex(@"/(@)\w+/g");
var listOfFound = r.Match(note);

I'm hoping listOfFound will be an array or a List containing the three values.

I could do this with some clever string parsing, but it seems like this should be a piece of cake for RegEx, if I could only come up with the right pattern.

Thanks for any help!

Rob Schripsema
  • 103
  • 1
  • 7

3 Answers3

2

Regexes in C# don't need delimiters and options must be supplied as the second argument to the constructor, but are not required in this case as you can get all your matches using Regex.Matches. Note that by using a lookbehind for the @ ((?<=@)) we can avoid having the @ in the match:

string note = "Hello, @bob and @mark and @dave";
Regex r = new Regex(@"(?<=@)\w+");
foreach (Match match in r.Matches(note))
    Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index);

Output:

Found 'bob' at position 8
Found 'mark' at position 17
Found 'dave' at position 27

To get all the values into a list/array you could use something like:

string note = "Hello, @bob and @mark and @dave";
Regex r = new Regex(@"(?<=@)\w+");
// list of matches
List<String> Matches = new List<String>();
foreach (Match match in r.Matches(note))
    Matches.Add(match.Value);
// array of matches
String[] listOfFound = Matches.ToArray();
Nick
  • 138,499
  • 22
  • 57
  • 95
0

You could do it without Regex, for example:

var listOfFound = note.Split().Where(word => word.StartsWith("@"));
xagyg
  • 9,562
  • 2
  • 32
  • 29
-1

Replace

var listOfFound = r.Match(note);

by

var listOfFound = r.Matches(note);
Mohamed Farouk
  • 1,089
  • 5
  • 10