简体   繁体   English

删除字符串的转义字符

[英]Removing Escape Characters for a string

I am having a bit of a problem with Escape characters is a string that I am reading from a txt file, They are causing an error later in my program, they need to be removed but I can't seem to filter them out我对转义字符有点问题是我从 txt 文件中读取的字符串,它们稍后会在我的程序中导致错误,它们需要被删除,但我似乎无法过滤掉它们

  public static List<string> loadData(string type)
    {
        List<string> dataList = new List<string>();
        try
        {
            string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Data");
            string text = File.ReadAllText(path + type);


            string[] dataArray = text.Split(',');


            foreach (var data in dataArray)
            {
                string dataUnescaped = Regex.Unescape(data);
                if (!string.IsNullOrEmpty(dataUnescaped) && (!dataUnescaped.Contains(@"\r") || (!dataUnescaped.Contains(@"\n"))))
                {
                    dataList.Add(data);
                }
            }
            return dataList;
        }
        catch(Exception e)
        {
            Console.WriteLine(e);
            return dataList;
        }
    }

I have tried text.Replace(@"\r\n") and an if statement but I just cant seem to remove them from my string我试过 text.Replace(@"\r\n") 和 if 语句,但我似乎无法将它们从我的字符串中删除

Any ideas will be appreciated任何想法将不胜感激

If you add the @ Sign before a string that means you specify that you want a string without having to escape any characters.如果在字符串前添加@符号,则表示您指定需要一个字符串而无需转义任何字符。

So if you wanted a path without @ you would need to do this:所以如果你想要一个没有@的路径,你需要这样做:

string s = "c:\\myfolder\\myfile.txt"

But if you add the @ before your \n\r isntead of the escaped sequence Windows New Line you would instead get the string "\n\r" .但是,如果您在\n\r之前添加@而不是转义序列 Windows New Line,您将得到字符串"\n\r"

So this will result in you removing all occurrences of the string "\n\r" .因此,这将导致您删除所有出现的字符串"\n\r" Instead of NewLines like you want to:而不是像你想要的 NewLines:

text.Replace(@"\r\n")

To fix that you would need to use:要解决这个问题,您需要使用:

text = text.Replace(Environment.NewLine, string.Empty);

You can use Environment.NewLine as well instead of \r and \n , because Environment knows which OS you are currently on and change the replaced character depeding on that.您也可以使用Environment.NewLine而不是\r\n ,因为 Environment 知道您当前使用的是哪个操作系统,并根据该操作系统更改替换字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM