Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the contents of square brackets in a string of text in c# using Regex

Tags:

c#

regex

match

if i have a string of text like below, how can i collect the contents of the brackets in a collection in c# even if it goes over line breaks?

eg...

string s = "test [4df] test [5yu] test [6nf]";

should give me..

collection[0] = 4df

collection[1] = 5yu

collection[2] = 6nf

like image 869
Grant Avatar asked Nov 28 '09 00:11

Grant


2 Answers

You can do this with regular expressions, and a bit of Linq.

    string s = "test [4df] test [5y" + Environment.NewLine + "u] test [6nf]";

    ICollection<string> matches =
        Regex.Matches(s.Replace(Environment.NewLine, ""), @"\[([^]]*)\]")
            .Cast<Match>()
            .Select(x => x.Groups[1].Value)
            .ToList();

    foreach (string match in matches)
        Console.WriteLine(match);

Output:

4df
5yu
6nf

Here's what the regular expression means:

\[   : Match a literal [
(    : Start a new group, match.Groups[1]
[^]] : Match any character except ]
*    : 0 or more of the above
)    : Close the group
\]   : Literal ]
like image 136
Mark Byers Avatar answered Oct 18 '22 18:10

Mark Byers


Regex regex = new Regex(@"\[[^\]]+\]", RegexOptions.Multiline);
like image 32
Thomas Levesque Avatar answered Oct 18 '22 18:10

Thomas Levesque