Shahid Sultan Minhas
Shahid Sultan Minhas

Reputation: 61

How to find number of all occurrences of the last written Word/String in rich text box?

I have a rich text box in which i am triggering the keypress event with spacebar. The logic to find number of all occurrences of the last written word which i have implemented is:

private void textContainer_rtb_KeyPress_1(object sender, KeyPressEventArgs e)
    {
        //String lastWordToFind;
        if (e.KeyChar == ' ')
        {
            int i = textContainer_rtb.Text.TrimEnd().LastIndexOf(' ');
            if (i != -1)
            {
                String lastWordToFind = textContainer_rtb.Text.Substring(i + 1).TrimEnd();

                int count = new Regex(lastWordToFind).Matches(this.textContainer_rtb.Text.Split(' ').ToString()).Count;
                MessageBox.Show("Word: " + lastWordToFind + "has come: " + count + "times");
            }

        }
    }

But its not working. Can somebody please point out the error or rectify it?

Upvotes: 0

Views: 676

Answers (2)

Kami
Kami

Reputation: 19407

You Regex appears to be incorrect. Try the following.

String lastWordToFind = textContainer_rtb.Text.Substring(i + 1).TrimEnd();
// Match only whole words not partial matches
// Remove if partial matches are okay
lastWordToFind = @"\b" + word + @"\b";

Console.WriteLine(Regex.Matches(richTextBox1.Text, word).Count);

Upvotes: 0

Arie
Arie

Reputation: 5373

regex doesn't work lilke this:

int count = new Regex(lastWordToFind).Matches(this.textContainer_rtb.Text.Split(' ').ToString()).Count;

this part:

this.textContainer_rtb.Text.Split(' ').ToString()

will split your text into array of strings:

string s = "sss sss sss aaa sss";
string [] arr = s.Split(' '); 

arr is like this after split:

arr[0]=="sss"
arr[1]=="sss"
arr[2]=="sss"
arr[3]=="aaa"
arr[4]=="sss"

then ToString() returns type name:

System.String[]

So what you're really doing is:

int count = new Regex("ccc").Matches("System.String[]").Count;

That's why it doesn't work. You should simply do:

 int count = new Regex(lastWordToFind).Matches(this.textContainer_rtb.Text).Count;

Upvotes: 1

Related Questions