string.IndexOf搜索整个单词匹配

D J*_*D J 6 c# regex string substring indexof

我正在寻找一种方法来搜索字符串以获得完全匹配或完整的单词匹配. RegEx.Match并且RegEx.IsMatch似乎没有让我在哪里,我想.
请考虑以下情形:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

上面代码的输出是:

// 34.37
// Press any key to continue...
Run Code Online (Sandbox Code Playgroud)

问题是,我不想SUBTOTAL的,但IndexOf发现这个词第一次出现TOTAL是在SUBTOTAL然后得到34.37的不正确的值.

所以问题是,有没有办法强制IndexOf只找到一个完全匹配或是否有另一种方法来强制完全匹配的单词,以便我可以找到该完全匹配的索引,然后用它执行一些有用的功能.RegEx.IsMatch并且RegEx.Match是,据我所知道的,只是boolean搜索.在这种情况下,仅知道存在完全匹配是不够的.我需要知道它在字符串中的位置.

任何意见,将不胜感激.

L.B*_*L.B 9

你可以使用Regex

string str = "SUBTOTAL 34.37 TAX TOTAL 37.43";
var indx = Regex.Match(str, @"\WTOTAL\W").Index; // will be 18
Run Code Online (Sandbox Code Playgroud)


pal*_*ota 5

我的方法比接受的答案更快,因为它不使用正则表达式。

string str = "SUBTOTAL 34.37 TAX TOTAL 37.43";
var indx = str.IndexOfWholeWord("TOTAL");

public static int IndexOfWholeWord(this string str, string word)
{
    for (int j = 0; j < str.Length && 
        (j = str.IndexOf(word, j, StringComparison.Ordinal)) >= 0; j++)
        if ((j == 0 || !char.IsLetterOrDigit(str, j - 1)) && 
            (j + word.Length == str.Length || !char.IsLetterOrDigit(str, j + word.Length)))
            return j;
    return -1;
}
Run Code Online (Sandbox Code Playgroud)