user6166859
user6166859

Reputation: 15

Find all instances of numbers in the text in a wpf richtextbox

I have a winform application where I need to provide the capability of finding and highlighting all numbers in the text entered by the user. For this I am adding a wpf richtextbox to a element host on the form. On the click of a button, I read the text in the textbox to find all the numbers. The issue is that only the last instance of the number is being highlighted and not all instances. For ex - in the text - "The order is for 12 bagels. The address is 13456 Lame st." only 13456 gets highlighted. The code is below:

    private void btnSave_Click(object sender, EventArgs e)
    {
        var wpfTextBox = (System.Windows.Controls.RichTextBox)elementHost1.Child;
        Regex reg = new Regex("[0-9 -()+]+$"); 
        var start = wpfTextBox.Document.ContentStart;
        while (start != null && start.CompareTo(wpfTextBox.Document.ContentEnd) < 0)
        {
            if (start.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
            {
                var match = reg.Match(start.GetTextInRun(LogicalDirection.Forward));

                var textrange = new TextRange(start.GetPositionAtOffset(match.Index, LogicalDirection.Forward), start.GetPositionAtOffset(match.Index + match.Length, LogicalDirection.Backward));
                textrange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Blue));
          }
            start = start.GetNextContextPosition(LogicalDirection.Forward);

        }

    }

Thank you for your time!

Upvotes: 0

Views: 289

Answers (1)

mark_h
mark_h

Reputation: 5477

Your code for highlighting seems to work fine but I ran your regex in a tester and it did not pick up any numbers in the string you provided. To highlight all numbers in the string you provided I replaced your regex with this;

Regex reg = new Regex(@"\d+");

Although this does highlight the numbers in the specific example you gave it may not match everything you want in all cases. To fine-tune the regex I strongly recommend using an online tool like the one I linked to above.

Upvotes: 2

Related Questions