Find specific text in RichTextBox and set it to a string c#

后端 未结 4 1123
一向
一向 2021-01-28 13:56

I am at a loss as to how to do this. I am printing some information to a richtextbox that will be multiple lines, has words and numbers. I need to search the richtextbox for spe

相关标签:
4条回答
  • 2021-01-28 14:06

    With regex, you can have:

    string pattern = @"[0-9]+";
    string input = @"Matt's number for today 
    is 33 and OK.";
    RegexOptions options = RegexOptions.Multiline;
    
    Console.WriteLine("Matt's number is: {0}", Regex.Matches(input, pattern, options)[0].Value);
    
    0 讨论(0)
  • 2021-01-28 14:09
    1. Use String.Split to parse the string into an array
    2. Iterate array and use Int32.TrParse method to determine if the "word" is in fact a number

          var input = "User: Matt  User's number: 10";
          int num = 0;
          foreach(var word in input.Split(' '))
          {
              if (Int32.TryParse(word, out num) && Enumerable.Range(1,30).Contains(num))
              {
                  Console.WriteLine("The user number is " + num);
                  break;
              }
          }
      

    or with linq:

            int testNum;
            var digits = input.Split(' ').Where(a => Int32.TryParse(a, out testNum) && Enumerable.Range(1, 30).Contains(testNum)).FirstOrDefault();
            Console.WriteLine("Linq The user number is " + (!string.IsNullOrEmpty(digits) ? digits : "Not Found"));
    
    0 讨论(0)
  • 2021-01-28 14:13

    You can use a Linq query to find the number like below:

    var nums = Enumerable.Range(1,30).Select(x => x.ToString());
    var num = richtextbox1.Text.Split(' ')
                          .Where(x => numStr.Contains(x))
                          .Single();
    Console.WriteLine("The user number is " + num);
    
    0 讨论(0)
  • 2021-01-28 14:30

    It seems like regular expressions might be useful here. Otherwise, if you know there will only be one number in the textbox, you could select all the chars that are digits and initialize a new string from the array:

    var digitArray = richtextbox1.Text.Where(Char.IsDigit).ToArray();
    string userNum = new String(digitArray);
    Messagebox.Show("The User's Number is " + userNum);
    
    0 讨论(0)
提交回复
热议问题