c# - string.IndexOf 搜索全词匹配

标签 c# regex string substring indexof

我正在寻找一种方法来搜索字符串以进行完全匹配或全字匹配。 RegEx.MatchRegEx.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();
        }
    }
}

以上代码的输出为:

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

问题是,我不想要 SUBTOTAL,但是 IndexOf 找到了单词 的第一次出现SUBTOTAL 中的 TOTAL 会产生错误的值 34.37。

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

如有任何建议,我们将不胜感激。

最佳答案

你可以使用正则表达式

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

关于c# - string.IndexOf 搜索全词匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24437274/

相关文章:

javascript - 无效的字符串长度/分配大小重载 JavaScript

c# - 内存不足故障自动化 VSTO Powerpoint API

c# - 在连接到 CRM 的 LINQ 表达式中排除数组

c# - DbMigrator 不提交对数据库的更改

javascript - 正则表达式:从 JavaScript 中的字符串获取高度值

c# - 在字符串 : "Input string was not in a correct format" 中使用括号时

c# - 将属性作为参数传递

java - 正则表达式: ignore what is quoted in a string

javascript - 在 JavaScript 中通过正则表达式查找字符串

c# - 将整数输入保存到数组中