c# – string.IndexOf搜索整个单词匹配

前端之家收集整理的这篇文章主要介绍了c# – string.IndexOf搜索整个单词匹配前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在寻找一种方法搜索字符串以获得完全匹配或完整的单词匹配. RegEx.Match和RegEx.IsMatch似乎没有让我到达我想要的地方.请考虑以下情形:
  1. namespace test
  2. {
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. string str = "SUBTOTAL 34.37 TAX TOTAL 37.43";
  8. int indx = str.IndexOf("TOTAL");
  9. string amount = str.Substring(indx + "TOTAL".Length,10);
  10. string strAmount = Regex.Replace(amount,"[^.0-9]","");
  11.  
  12. Console.WriteLine(strAmount);
  13. Console.WriteLine("Press any key to continue...");
  14. Console.ReadKey();
  15. }
  16. }
  17. }

上面代码输出是:

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

问题是,我不想要SUBTOTAL,但是IndexOf找到第一次出现的单词TOTAL,它在SUBTOTAL中,然后产生不正确的值34.37.

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

任何意见,将不胜感激.

解决方法

你可以使用Regex
  1. string str = "SUBTOTAL 34.37 TAX TOTAL 37.43";
  2. var indx = Regex.Match(str,@"\WTOTAL\W").Index; // will be 18

猜你在找的C#相关文章