Regex.Match (I get wrong Match.Index when in string there is \n); RRS feed

  • Question

  • I have 2 textBoxes(FindWhatTextBox,MyTextBox) and button

    for example this.MyTextBox.Text = "Hello \r\n My name is Anton";

    and             this.FindWhatTextBox.Text = "name";

    buttonClick(object sender, EventArgs e)


    Regex regex = new Regex(this.FindWhatTextBox.Text);

    Match match = regex.Match(this.MyTextBox.Text);

    this.MyTextBox.Select(match.Index, this.FindWhatTextBox.Text.Length);


    So, after click it select "ame ", but not "name".
    What I should to do?

    Best regards Em Anton

    Wednesday, April 22, 2015 9:32 AM


  • The following code should select "name":

            public Form1()
                this.MyTextBox.Text = "Hello \r\n My name is Anton";
                this.FindWhatTextBox.Text = "name";
                Regex regex = new Regex(this.FindWhatTextBox.Text);
                Match match = regex.Match(this.MyTextBox.Text);
                this.MyTextBox.SelectionStart = match.Index;
                this.MyTextBox.SelectionLength = this.FindWhatTextBox.Text.Length;
                string selectedText = this.MyTextBox.SelectedText; // = "name"

    Please remember to mark helpful posts as answer to close your threads and then start a new thread if you have a new question. Please don't ask several questions in the same thread.

    • Proposed as answer by Kristin Xie Thursday, April 23, 2015 3:08 AM
    • Marked as answer by Fred Bao Thursday, April 30, 2015 3:17 AM
    Wednesday, April 22, 2015 10:48 AM