【问题标题】:Remove characters from List<string> in between separators (from text file)从分隔符之间的 List<string> 中删除字符(来自文本文件)
【发布时间】:2020-02-09 23:59:03
【问题描述】:

快速替换文本文件中的文本。 来自:somename@somedomain.com:hello_world 至此:somename:hello_world

它需要是 FAST 并且支持多行文本文件。

我尝试将字符串分成三个部分,但它似乎很慢。下面代码中的示例。

<pre><code>
    public static void Conversion()
    {
        List<string> list = File.ReadAllLines("ETU/Tut.txt").ToList();
        Console.WriteLine("Please wait, converting in progress !");

        foreach (string combination in list)
        {
            if (combination.Contains("@"))
            {

            write: try
                {
                    using (StreamWriter sw = new 
                    StreamWriter("ETU/UPCombination.txt", true))
                    {
                        sw.WriteLine(combination.Split('@', ':')[0] + ":" 
                        + combination.Split('@', ':')[2]);
                    }
                }
                catch
                {
                    goto write;
                }
            }
            else
            {
                Console.WriteLine("At least one line doesn't contain @");
            }

        }


    }</code></pre>

这是一种将文本文件中的每一行从 somename@somedomain.com:hello_world

收件人:somename:hello_world 然后将其保存为不同的文本文件。

!记住域位总是变化的!

【问题讨论】:

  • 请准确解释您要对输入文本执行的操作。

标签: c# regex list visual-studio replace


【解决方案1】:

很可能不是最快的,但它非常快,表达类似于,

@[^:]+

并将其替换为空字符串。

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"@[^:]+";
        string substitution = @"";
        string input = @"somename@somedomain.com:hello_world1
somename@some_other_domain.com:hello_world2";
        RegexOptions options = RegexOptions.Multiline;

        Regex regex = new Regex(pattern, options);
        string result = regex.Replace(input, substitution);
    }
}

如果您希望简化/修改/探索表达式,在regex101.com 的右上角面板中已对此进行了说明。如果您愿意,您还可以在this link 中观看它如何与一些示例输入匹配。


正则表达式电路

jex.im 可视化正则表达式:

【讨论】:

  • 1) RegexOptions options = RegexOptions.Multiline; 是多余的,因为正则表达式没有可修改的锚点,2) 使用正则表达式实例 Replace 方法不会使其更快,静态 Regex.Replace 会更快。事实上,为了加快速度,正则表达式应该是带有RegexOptions.Compiled 选项的静态只读私有字段。然后,它几乎和 LINQ 一样快。
猜你喜欢
  • 1970-01-01
  • 2020-03-28
  • 1970-01-01
  • 1970-01-01
  • 2019-05-15
  • 2016-11-20
  • 2013-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多