locked
Getting Unterminated [ ] set exception in Regex RRS feed

  • Question

  • User321489315 posted

    Hi All, 

    I am getting "parsing "[]" - Unterminated [] set."  exception while splitting string with Regular expression for below string

    string studentinfo = "Student Info : \n[]Student Attendance \n[]Student Lunch Time\n[]Student Play time\n[]Student Library time, \nStudent Class room Info : \n[]Maths Class Time \n[]Physics Class Time \n[]GK Class Time \n\nFinal Report";
                List<string> pattern = new List<string>();
                pattern.Add("[]");
                string[] studentRecord = null;
    
                try
                {
                    if (studentinfo != null && pattern != null)
                    {
                        studentRecord = Regex.Split(studentinfo, @"" + pattern[0] + "", RegexOptions.IgnoreCase).Where(s => s.Contains(pattern[0]) && s != string.Empty).ToArray().Select(p => p.Replace(pattern[0], string.Empty)).ToArray();
                    }
                }
                catch (Exception e)
                {
    
                }

    what is the mistake here? please help me

    Thanks

    Chandu

    Thursday, July 26, 2018 6:23 AM

Answers

  • User1520731567 posted

    Hi chandu_king,

    Since [] are metacharacters in Regex,I suggest you could add '\' to escape.

    You could modify the code below:

     pattern.Add("[]");

    to:

    pattern.Add("\\[\\]");

    How it works:

    Best Regards.

    Yuki Tao

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 27, 2018 8:02 AM

All replies

  • User-821857111 posted

    [] are metacharacters in Regex. If you intend to look for them literally, you need to escape them:

    pattern.Add(@"\[\]");

    Thursday, July 26, 2018 7:22 AM
  • User1520731567 posted

    Hi chandu_king,

    Since [] are metacharacters in Regex,I suggest you could add '\' to escape.

    You could modify the code below:

     pattern.Add("[]");

    to:

    pattern.Add("\\[\\]");

    How it works:

    Best Regards.

    Yuki Tao

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 27, 2018 8:02 AM