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
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);
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"));
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);
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);