繁体   English   中英

字符串替换()/正则表达式替换-替换字符串数组中的字符串?

[英]String Replace()/regex replace - Replacing strings in array of strings?

我正在编写一个控制台应用程序,该程序从csv文件中读取数据并将文件中的每个元素存储到字符串数组中。 我有一种方法要遍历数组中的每个字符串并删除所有非字母字符和空格。 我成功使用regex.replace()使用字符串完成了此操作,但是当我尝试使用字符串数组进行更改后,这种情况发生了变化。 然后,我继续尝试使用string.replace(),但无济于事。 我认为正则表达式路径是更好的选择,但我还没有成功。 如果有人可以帮助我,我将不胜感激。 到目前为止,这是我的代码:

    public static string[] ChangeAddress(string[] address)
    {
        for (int i = 0; i < address.Length; i++)
        {
            Regex.Replace(i, @"(\s-|[^A-Za-z])", ""); 
            System.Console.WriteLine(address[i]);
        }
        return address;
    }

    static void Main(string[] args)
    {
        string[] address = null;
        //try...catch read file, throws error if unable to read
        //reads file and stores values in array
        try
        {
            StreamReader sr = new StreamReader("test.csv");
            string strLine = "";
            //while not at the end of the file, add to array
            while (!sr.EndOfStream)
            {
                strLine = sr.ReadLine();
                address = strLine.Split(',');
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("File could no be read:");
            Console.WriteLine(e.Message);
        }

        //calls ChangeAddress method
        ChangeAddress(address);
    }

csv文件包含用逗号分隔的不同地址。 我的目标是删除数字,只留下街道名称。 例如,原始字符串可能是123个伪造的字符串,目标是删除“ 123”,以便将其替换为“ fake”。 我想对数组中的每个元素执行此操作。

替换时,您需要对结果做些事情,以下类似的事情应该可以解决。

public static string[] ChangeAddress(string[] address)
{
    for (int i = 0; i < address.Length; i++)
    {
        address[i] = Regex.Replace(address[i], @"(\s-|[^A-Za-z])", ""); 
        System.Console.WriteLine(address[i]);
    }
    return address;
}

这里的关键是您必须将值传递给RegEx.Replace并更新数组。

除了米切尔的答案,这是一个问题:

StreamReader sr = new StreamReader("test.csv");
string strLine = "";

//while not at the end of the file, add to array
while (!sr.EndOfStream)
{
   strLine = sr.ReadLine();
   address = strLine.Split(',');
}

...,并可以替换为File.ReadAllLines

addresses = File.ReadAllLines("test.csv");

您可以使用File.ReadLines并动态修复地址:

var addresses = new List<string>();
foreach(var address in File.Readlines("test.csv"))
{
    var corrected = Regex.Replace(address, @"(\s-|[^A-Za-z])", "");
    addresses.Add(corrected);
}

为什么不将正则表达式替换项应用于strLine,然后再将其放入地址数组? 您可以执行以下操作:

`Regex.Replace(strLine, @"(\s-|[^A-Za-z])", "");`
`address = strLine.Split(',');`

当然,您可能希望修改正则表达式以不删除','。

暂无
暂无

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

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