1

hye, I got this error "An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in System.dll" while doing this split code. the error occur at code textBox1.Text= mc[0].Groups[1].Value;

        var desiredText = File.ReadLines(location).ElementAt(i);
        string s = desiredText.ToString();
        //textBox3.Text = s;
        Regex r = new Regex(@"[(.+?)]");
        MatchCollection mc = r.Matches(s);
        textBox1.Text= mc[0].Groups[1].Value;
        textBox2.Text= mc[1].Groups[1].Value;
        textBox3.Text = mc[2].Groups[1].Value;

where did I do wrong? the textfile that I used have this data

[1] [apple] [market]
[2][toy]asdv[shop]sdvdsrdt

3 Answers3

1

Your regex should probably escape the square brackets:

Regex r = new Regex(@"\[(.+?)\]");
Community
  • 1
  • 1
Eugene Podskal
  • 10,270
  • 5
  • 31
  • 53
1

In Regex, [Brackets] define a Character Class

  • In regex, [brackets] have a special meaning: they define a character class. A character class matches one of the characters it contains. For instance, [abc] matches either an a, a b or a c. You can also define a range: [a-c] matches the same characters.
  • The regex [(.+?)] therefore matches one single character that is either a (, a ), a + or a ?
  • To match actual brackets, you need to escape them with a \. This is what you want: \[(.+?)\]

Therefore, in C#:

Regex r = new Regex(@"\[(.+?)\]");

Reference

Character Classes or Character Sets

zx81
  • 41,100
  • 9
  • 89
  • 105
1

The way you have your brackets, the regular expression engine considers it as a Character Class matching any of those characters that are placed inside. You need to escape your brackets in order to match a literal.

string s = @"[1] [apple] [market]";

Regex r = new Regex(@"\[(.+?)\]");
MatchCollection mc = r.Matches(s);

Console.WriteLine(mc[0].Groups[1].Value); //=> 1
Console.WriteLine(mc[1].Groups[1].Value); //=> apple
Console.WriteLine(mc[2].Groups[1].Value); //=> market
hwnd
  • 69,796
  • 4
  • 95
  • 132