【发布时间】:2014-08-17 16:55:05
【问题描述】:
我正在寻找一种方法来搜索字符串以进行完全匹配或整个单词匹配。 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 找到了 TOTAL 一词的第一次出现在 SUBTOTAL 然后产生不正确的值 34.37。
所以问题是,有没有办法强制 IndexOf 只找到一个完全匹配,或者有没有另一种方法来强制完全匹配整个单词,这样我就可以找到那个完全匹配的索引,然后执行一些有用的功能。 RegEx.IsMatch 和 RegEx.Match 是,据我所知,只是 boolean 搜索。在这种情况下,仅仅知道存在精确匹配是不够的。我需要知道它在字符串中的位置。
任何建议将不胜感激。
【问题讨论】:
-
str.IndexOf(" TOTAL ");但是很丑。
标签: c# regex string substring indexof