我正在寻找一种方法来搜索字符串以进行完全匹配或全字匹配。 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();
}
}
}
以上代码的输出为:
// 34.37
// Press any key to continue...
问题是,我不想要 SUBTOTAL
,但是 IndexOf
找到了单词 的第一次出现
会产生错误的值 34.37。 SUBTOTAL
中的 TOTAL
所以问题是,有没有一种方法可以强制 IndexOf
只找到完全匹配,或者是否有另一种方法可以强制完全匹配整个单词,以便我可以找到那个精确匹配的索引匹配然后用它执行一些有用的功能。据我所知,RegEx.IsMatch
和 RegEx.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/