How to extract the contents of square brackets in a line of text in C # using Regex

if I have a line of text as shown below, how can I collect the contents of the brackets in a collection in C #, even if it goes through line breaks?

eg,...

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

should give me ..

collection [0] = 4df

collection [1] = 5yu

collection [2] = 6nf

+7
c # regex match
source share
4 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 is what 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 ] 
+16
source share
 Regex regex = new Regex(@"\[[^\]]+\]", RegexOptions.Multiline); 
+3
source share

The key is to correctly avoid the special characters used in regular expressions, for example, you can match the character [ as follows: @"\["

+1
source share
 Regex rx = new Regex(@"\[.+?\]"); var collection = rx.Matches(s); 

You will need to trim the square brackets, the important part is the lazy operator.

0
source share

All Articles