locked
What is the mistake here? RRS feed

  • Question

  • Hello All, 

    I have below string to split with multiple patterns. I am not getting result as expected. 

    for eg : 

    string text="cat[__]dog[__]animal[__]person(__)abc[__]dog1[__]animal1(__)person2[***]iobdb[***]blabla[&&&]defbla[&&&]defosb";
    
    
    List<string> pattern = new List<string>();
    pattern.Add("[__]");
    pattern.Add("[***]");
    pattern.Add("[&&&]");
    
    string[] result = null;
    result = Regex.Split(text , @"(" + String.Join("|", pattern.ToArray()) + ")");

    I tried with the regular expressions. but result not getting as expected. It's not splitting(eg. "[__]") exactly what i declared in the pattern array. What is the mistake here?

    Thanks,
    Chandu


    Wednesday, June 13, 2018 9:02 AM

Answers

  • You need to learn that you have to escape the special characters of the Regular Expression Language, like ". $ ^ { [ ( | ) * + ? |". Otherwise you'll always get the wrong results.

    Try:

    string text = "cat[__]dog[__]animal[__]person(__)abc[__]dog1[__]animal1(__)person2[***]iobdb[***]blabla[&&&]defbla[&&&]defosb";
    
    
    List<string> pattern = new List<string>();
    pattern.Add(Regex.Escape(@"[__]"));
    pattern.Add(Regex.Escape(@"[***]"));
    pattern.Add(Regex.Escape(@"[&&&]"));
    string pStr = string.Join("|", pattern.ToArray());
    
    Regex.Split(text, pStr).ToList().ForEach(Console.WriteLine);

    I used the Regex.Escape method to escape those special characters within your pattern strings, you can do it manually by putting escape character backslash "\" in front of them as well. 

    And, I scrapped your additional parenthesisses around your joined pattern string, because they had also a special meaning.

    I added the line "string pStr = ..." so that you can set a breakpoint here to see how your pattern looks, after those escaping.

    wizend



    Wednesday, June 13, 2018 10:02 AM