c# - 如何在 C# 中搜索多个位置的直接子字符串

标签 c# regex string substring

<分区>

我有一个字符串,我需要将其分解为多个子字符串。现在根据我的条件,在分解为子字符串时,我必须在字符串中搜索两个文本。这是我的两个文本..

  1. 1。 2 To Other Mobiles(这可能会根据子字符串中需要的条件而改变)
  2. 总计(这是子串的最后一个)

这是我的示例字符串内容

1 . 1 To Airtel Mobile
1 03/MAR/2013 16:06:31 9845070641 05:44 1.80 **
2 04/MAR/2013 10:00:29 9845096416 00:14 0.30 **
Total 25:28 9.30
1 . 2 To Other Mobiles
1 03/MAR/2013 06:41:06 9448485859 00:15 0.40 **
2 04/MAR/2013 18:57:47 9448367847 08:33 3.60 **
3 05/MAR/2013 18:57:05 9448485859 00:42 0.40 **
4 05/MAR/2013 20:13:19 9448367847 00:42 0.40 **
Total 34:33 18.00
1 . 3 To Fixed Landline
21 21/MAR/2013 11:59:35 08066000000 09:34 5.00
22 22/MAR/2013 11:31:33 08066000000 15:20 8.00
Total 01:35:23 54.00

根据这两个文本的索引,我将字符串分解为子字符串。现在根据我的条件,我必须将子字符串读取到直接文本,即 Total

但在我现在的代码中,我正在读取字符串到子字符串,直到最后一个 Total 文本。

这是我的代码:

string search1 = "1 . 2 To Other Mobiles";
string search2 = "Total";

int startPosition = currentText.IndexOf(search1);
if (startPosition >= 0)
{
    startPosition += search1.Length;
    int endPosition = currentText.LastIndexOf(search2);
    if (endPosition > startPosition)
    {
        string result = currentText.Substring(startPosition, endPosition - startPosition);
    }
}

简而言之,我必须搜索第一个可搜索文本并开始阅读直到第二个文本。

最佳答案

在 LinqPad 中完成的没有 Regex 的解决方案:

string source = @"1 . 1 To Airtel Mobile
1 03/MAR/2013 16:06:31 9845070641 05:44 1.80 **
2 04/MAR/2013 10:00:29 9845096416 00:14 0.30 **
Total 25:28 9.30
1 . 2 To Other Mobiles
1 03/MAR/2013 06:41:06 9448485859 00:15 0.40 **
2 04/MAR/2013 18:57:47 9448367847 08:33 3.60 **
3 05/MAR/2013 18:57:05 9448485859 00:42 0.40 **
4 05/MAR/2013 20:13:19 9448367847 00:42 0.40 **
Total 34:33 18.00
1 . 3 To Fixed Landline
21 21/MAR/2013 11:59:35 08066000000 09:34 5.00
22 22/MAR/2013 11:31:33 08066000000 15:20 8.00
Total 01:35:23 54.00";

string search1 = "1 . 2 To Other Mobiles";
string search2 = "Total";

var result = source.Split(new string[] { search1 }, StringSplitOptions.None)[1].
                    Split(new string[] { search2 }, StringSplitOptions.None)[0].
                    Dump();

输出:

1 03/MAR/2013 06:41:06 9448485859 00:15 0.40 **
2 04/MAR/2013 18:57:47 9448367847 08:33 3.60 **
3 05/MAR/2013 18:57:05 9448485859 00:42 0.40 **
4 05/MAR/2013 20:13:19 9448367847 00:42 0.40 **

根据对您问题的评论,我推测您不希望搜索词出现在输出中,是吗?

如果您需要重复搜索具有相同开始和结束参数的文本 block ,您可以将其包装在一个方法中并让它递归地从拆分索引 [1] 开始。

关于c# - 如何在 C# 中搜索多个位置的直接子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21877358/

相关文章:

mysql - 由于 appcelerator 中错误的字符串连接而导致参数化执行查询中断

file-io - 在 clojure 中,为什么从空文件中分割字符串会返回 1 个元素?

c#启动一个任务需要多长时间

c# - WebClient.DownloadProgressChanged 永远不会被调用

c# - 多个图钉 Bing map Windows Phone 7

javascript - 包含 HTML 标签但仅包含字符列表

c# - 动态添加的 LinkBut​​ton CommandName/CommandArgument 设置被删除

python - 使用正则表达式从电子邮件中捕获日期

python - 从 python 中的字符串中删除 LaTeX 字符

android - TextView.getText().toString() 与 TextView.toString()