jeudi 26 juin 2014

string.IndexOf search for whole word match


Vote count:

0




I am seeking a way to search a string for an exact match or whole word match. RegEx.Match and RegEx.IsMatch don't seem to get me where I want to be. Consider the following scenario:



namespace test
{
class Program
{
static void Main(string[] args)
{
string str = "SUBTOTAL 34.37 TAX TOTAL 37.43";
int indx = str.IndexOf("TOTAL");
string amount = str.Substring(indx + "TOTAL".Length, 10);
string strAmount = Regex.Replace(amount, "[^.0-9]", "");

Console.WriteLine(strAmount);
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}


the output of the above code is:



// 34.37
// Press any key to continue...


The problem is, I don't want SUBTOTAL, but IndexOf finds the first occurrence of the word "TOTAL" which is in "SUBTOTAL" which then yields the incorrect value of 34.37.


So the question is, is there a way to force IndexOf to find only an exact match or is there another way to force that exact whole word match so that I can find the index of that exact match and then perform some useful function with it. RegEx.IsMatch and RegEx.Match are, as far as I can tell, simply boolean searches. In this case, it isn't enough to just know the exact match exists. I need to know where it exists in the string.


Any advice would be appreciated.



asked 40 secs ago






Aucun commentaire:

Enregistrer un commentaire